错误:带有multer和body-parser的json无效 [英] Error: invalid json with multer and body-parser

查看:235
本文介绍了错误:带有multer和body-parser的json无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在node.js应用程序中的multipart/form-data使用 multer body-parser .

I am currently using multer for multipart/form-data in node.js application alongside with body-parser.

我尝试使用POSTMAN POST 表单数据,但出现此错误.

I tried to POST form-data using POSTMAN, but it is getting this error.

Error: invalid json
    at parse (/Users/k/Documents/application/node_modules/body-parser/lib/types/json.js:79:15)
    at /Users/k/Documents/application/node_modules/body-parser/lib/read.js:102:18
    at IncomingMessage.onEnd (/Users/k/Documents/application/node_modules/body-parser/node_modules/raw-body/index.js:136:7)
    at IncomingMessage.g (events.js:199:16)
    at IncomingMessage.emit (events.js:104:17)
    at _stream_readable.js:908:16
    at process._tickDomainCallback (node.js:381:11)

这就是我在server.js中添加multer和body-parser的方式

This is how I added multer and body-parser in my server.js

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var multer = require('multer');

var app = express();

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(multer({ dest: './uploads/'}));

我认为这可能是因为multer无法正常运作.当我删除body-parser并重试时,它显示console.log(req.body)console.log(req.files)的空json.

I think it is probably because multer is not working. When I remove body-parser and try again, it shows empty json for console.log(req.body) and console.log(req.files).

注意:body-parser版本是 1.12.0 ,而multer版本是 0.1.8 .

Note: body-parser version is 1.12.0 and multer version is 0.1.8.

推荐答案

问题不在于您同时拥有库body-parsermulter.如果您尝试使用诸如postman之类的浏览器扩展程序进行发布,请确保在请求标头中Content-Typemultipart/form-data而不是application/json.

The problem is not that you have both libraries body-parser and multer. If you try to post with a browser extension like postman, please make sure Content-Type is multipart/form-data and not application/json in your request header.

这篇关于错误:带有multer和body-parser的json无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆