如何从表单数据中读取快速js中的数据

时间:2017-01-09 10:27:07

标签: node.js express angular2-routing

这是我可以在控制台中看到的请求有效负载

 ------WebKitFormBoundaryW5j4rbM04jMUgOkU
    Content-Disposition: form-data; name="file"; filename="Screenshot from 2016-12-12 18-34-26.png"
    Content-Type: image/png


    ------WebKitFormBoundaryW5j4rbM04jMUgOkU
    Content-Disposition: form-data; name="userId"

    12
    ------WebKitFormBoundaryW5j4rbM04jMUgOkU
    Content-Disposition: form-data; name="isAdmin"

    true
    ------WebKitFormBoundaryW5j4rbM04jMUgOkU--

我需要阅读userId哪里有

  

名="用户id"

    12

但是我的req.body是空白的json {}。怎么读这个

app.js

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

routes.js

    var employeeDocumentStorage = multer.diskStorage({
      destination: function (req, file, cb) {
****//need to read data here**** 
        console.log("uploading");
        console.log(file);
        var x = (JSON.parse(req.body));
        console.log(x)

        //var code = JSON.parse(req.body.model).empCode;
        var dest = 'public/documents/vss811/';
        mkdirp(dest, function (err) {
            if (err) cb(err, dest);
            else cb(null, dest);
        });
      },
      filename: function (req, file, cb) {
        cb(null, Date.now()+'-'+file.originalname);
      }
    });

2 个答案:

答案 0 :(得分:0)

尝试一下对我有用

const express = require('express');
const bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/', upload.none(), function (req, res) {
  // req.body would contain userId
  console.log("Data",req.body) 
  res.status(200).send('OK');
});

app.listen(port);

答案 1 :(得分:-1)

正如亚历克斯在评论中所说,你不会通过身体解析器得到这个。您的请求有效内容显示您似乎正在使用form-data内容类型。

您可以使用multer获取表单数据有效负载 - 并且您的路由已经显示您正在使用multer(var employeeDocumentStorage = multer.diskStorage({)):

const express = require('express')
const upload  = require('multer')({ dest: '/tmp/' });

app.post('/some-route', upload.single('name'), function (req, res, next) {
  console.log(req.body.userId); // should show 12
  console.log(req.files); // that's your file there.
  // do stuff.
});