如何使用Node / Multer在发布请求中捕获FormData

时间:2019-01-05 22:08:42

标签: node.js angular express multer

我基本上需要使用nodejs +在mongodb模式下保存一个formData 以后端表示,以中间件表示,该formData由字符串和Blob组成

我需要捕获blob和字符串,并以某种方式保存在数据库中,但是现在我什至无法在后端捕获

formData appends

我的req.body和我的req.files显示为未定义

预先感谢

按角度的邮政服务

addPost(message, blob): Observable<any> {
    var fd = new FormData();

    fd.append('id', message);
    fd.append('invoiceFile', blob);

    let httpHeaders = new HttpHeaders({
      Accept: 'multipart/form-data'
    });

    let options = {
      headers: httpHeaders
    };

    return this.http.post(`${addPost}`, fd, options);
  }

我的节点server.js

  const express = require('express');
  const mongoose = require('mongoose');
  const cookieParser = require('cookie-parser');
  // const morgan = require('morgan');
  const app = express();
  const cors = require('cors');
  var fs = require('fs');

  const dbConfig = require('./config/env');

  app.options('*', cors());
  app.use(cors({ credentials: true, origin: true }));

   app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Credentials', 'true');
  res.header('Access-Control-Allow-Methods', 'GET', 'POST', 'DELETE', 'PUT');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  );
  next();
});

   app.use(express.json({ limit: '50mb' }));
   app.use(express.urlencoded({ extended: true, limit: '50mb' }));

   app.use(logger('dev'));

   mongoose.Promise = global.Promise;
   mongoose.connect(
  dbConfig.url,
  { useNewUrlParser: true }
);

  const auth = require('./routes/authRoutes');
  const posts = require('./routes/postRoutes');
  app.use(cookieParser());
  app.use(auth);
  app.use(posts);

 app.listen(3000, () => {
     console.log('Runnning on port 3000');
});

我的路线

router.post('/api/post/add-post', upload.any(), function(req, res) {

  console.log(req.body); // appear as undefined
  console.log(req.file); // appear as undefined
  res.status(204).end();
});

1 个答案:

答案 0 :(得分:1)

尝试检查在发送表单时数据是否为空。 它应为jpg / jpeg或您要发送的格式。我的表单数据为空,所以我意识到我必须发送file.name,即“ image.jpg”,而不是整个文件的详细信息 在下面发送快照,看看是否有帮助 enter image description here