app.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * @Author: Johnhong9527
  3. * @Date: 2019-06-04 16:44:30
  4. * @Last Modified by: Johnhong9527
  5. * @Last Modified time: 2019-06-04 17:03:07
  6. */
  7. const express = require('express');
  8. const app = express();
  9. const fs = require('fs');
  10. var formidable = require('formidable');
  11. //allow custom header and CORS
  12. app.all('*', function(req, res, next) {
  13. res.header('Access-Control-Allow-Origin', '*');
  14. res.header(
  15. 'Access-Control-Allow-Headers',
  16. 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'
  17. );
  18. res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  19. if (req.method == 'OPTIONS') {
  20. res.send(200);
  21. /让options请求快速返回/;
  22. } else {
  23. next();
  24. }
  25. });
  26. app.post('/upload.do', (req, res) => {
  27. var form = new formidable.IncomingForm();
  28. console.log('about to parse');
  29. form.parse(req, function(error, fields, files) {
  30. console.log('parsing done');
  31. console.log(files);
  32. fs.writeFileSync('public/test.png', fs.readFileSync(files.upload.path));
  33. res.redirect('/public/upload.html');
  34. res.send({
  35. uid: Date.parse(new Date()) / 1000,
  36. url: ''
  37. });
  38. });
  39. /*作者:深蓝一人
  40. 链接:https://juejin.im/post/5a1a80a5f265da43333e1b88
  41. 来源:掘金
  42. 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/
  43. });
  44. app.get('/', (req, res) => {
  45. res.send('hello');
  46. });
  47. app.listen(3333, function() {
  48. console.log('to http://localhost:3333');
  49. });