为什么节点js +中的请求正文为空?

时间:2019-12-07 03:54:18

标签: javascript node.js reactjs express multipartform-data

我正在使用FormData发送发布请求。但是,当我在节点服务器上检查时,我的bodyblanked为什么? 我执行以下步骤

 let formData = new FormData();
                // add one or more of your files in FormData
                // again, the original file is located at the `originFileObj` key
                formData.append("file", values['Temp_id_card'].fileList[0].originFileObj);
                formData.append("Emp No",values['Emp No'].toLowerCase())
                formData.append("Remarks",values['Remarks'])
                formData.append("UpdatedStatus",values['Status'])
                formData.append("id",id)
                formData.append("Att Date",attDate)

像这样发送数据

export const sendPostRequest1 = (url, data, config = {}) => {
    let updatedConfig = {
        headers: {Authorization: `Bearer ${getAuthToken()}` || ""},
        ...config
    };
    return axios.post(url, data, updatedConfig);
}

当我在network上点击时,它显示数据已发送

enter image description here

但是在节点服务器上调试时,为什么显示为空体?

Node js代码

var Storage = multer.diskStorage({
    destination: function(req, file, callback) {
        if(req.user.userId === req.body.userId){
            callback(null, "./Images");
        }else {
            throw new AuthenticationError("Unauthorized User");
        }

    },
    filename: function(req, file, callback) {
        callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
    }
});
var upload = multer({
    storage: Storage
}).array("file", 1); //Field name and max count
router.post('/upload', (req, res) => {
    upload(req, res, function(err) {
        if (err) {
            return res.end("Something went wrong!");
        }
        return res.end("File uploaded successfully!.");
    });
});

当我在if(req.user.userId === req.body.userId){req.body上检查是否为空对象时?

我还添加了我的中间件

app.use(bodyParser.json({ limit: "100mb"}));
    app.use(bodyParser.urlencoded({ limit: "50mb",extended: false }));
    app.use(requestLogger);
    app.use(helmet());

1 个答案:

答案 0 :(得分:0)

获取了相同的问题(Angular + NodeJs),并在中间件的帮助下得以解决。

只要写
router.post('/ upload',upload.single('file'),(req,res,next)=> {
代替
router.post('/ upload',(req,res)=> {

For more details