我使用MongoDB作为我的节点/ Express应用程序的后端数据库。为了总结我面临的问题,我不知道如何在Express应用程序中设置body-parser配置,因为服务器端应用程序没有收到客户端应用程序发布的完整JSON(也是node.js应用程序)。大多数情况下,客户端将请求正文中的JSON发送到RESTful端点。例外情况是文件需要上传,并且由于它是一个多部分主体,因此我使用request和form-data来构建该类型的请求,并在服务器端使用multer来处理多部分请求,因为body-parser不处理这些请求。将JSON数据(使用节点请求)发布到Express服务器以保存到MongoDB中时遇到问题
在服务器端(快递),我有以下的快速应用程序的配置:
let app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
在节点客户端,我使用下面的代码建立一个JSON风格的JavaScript对象并张贴到一个RESTful端点:
我有困难撰写在客户端请求,与node-request:
// class is a JavaScript/JSON object within scope of this code
let req = request.post({
//headers: { 'Content-Type': 'application/json' },
url: 'http://localhost:3000/classes',
//form: class
form: JSON.stringify(class)
}, function (err, resp, body) {
if (err) {
throw err;
}
});
注意,我attem通过明确指定内容类型application/JSON
以及使用JSON.stringify
将JavaScript对象转换为JSON字符串,可以获得上述代码的多个版本。 MongoDB的集合(class
)存储以下类型的文档,其中包含外键到其他两个集合(subject
和student
):
{
"_id" : ObjectId("57758f15f68da08c254ebee1"),
"name" : "Grade 5 - Section A",
"scores" : [{
"studentId" : ObjectId("5776bd36ffc8227405d364d2"),
"performance": [{
"subjectId" : ObjectId("577694ecbf6f3a781759c54a"),
"score" : 86,
"maximum" : 100,
"grade" : "B+"
}]
}]
}
在服务器日志中,我看到了以下错误:
Tue, 05 Jul 2016 04:34:46 GMT classReportApp:routes:classes class received from client: { _id: 577b38e65967097c25876764, scores: [] }
RangeError: Invalid status code: 0
at ServerResponse.writeHead (_http_server.js:192:11)
at ServerResponse.writeHead (C:\Development\classReportApp\node_modules\morgan\node_modules\on-headers\index.js:55:19)
at ServerResponse._implicitHeader (_http_server.js:157:8)
at ServerResponse.OutgoingMessage.end (_http_outgoing.js:566:10)
at ServerResponse.send (C:\Development\classReportApp\node_modules\express\lib\response.js:205:10)
at ServerResponse.json (C:\Development\classReportApp\node_modules\express\lib\response.js:250:15)
at C:\Development\classReportApp\server-process\app.js:80:26
at Layer.handle_error (C:\Development\classReportApp\node_modules\express\lib\router\layer.js:71:5)
at trim_prefix (C:\Development\classReportApp\node_modules\express\lib\router\index.js:310:13)
at C:\Development\classReportApp\node_modules\express\lib\router\index.js:280:7
at Function.process_params (C:\Development\classReportApp\node_modules\express\lib\router\index.js:330:12)
这很奇怪,因为分数阵列的子文件是空的(scores: []
),而在客户端,我送了一些学生的表现元素一个非空数组在里面。
我违反了将JSON发布到Express应用程序的正确方法吗?我该如何解决?
修改于:2016年7月5日 我改变身体解析器中间件配置以使用extended: true
代替。
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
Node.js的依然采用node-request模块撰写和发送POST请求,使用下面的代码:
let req = request({
url: 'http://localhost:3000/classes',
method: 'POST',
json: class
}, function (err, resp, body) {
if (err) {
throw err;
}
else {
// process response
}
});
这工作了,但什么让我困惑的是,既然内容类型是application/json,bodyParser.urlencoded({ extended: true })
(或false)如何处理?
json是否在节点后端接收到它应该是(整个文档)? – cs04iz1
@ cs04iz1是的,它是整个文档,看起来字符串化。 –