[英]'undefined' object using MongoDB + Express
When I print client-side the received object on console using console.log(this.data)
, I get undefined
, so I cannot access data.body
to print the data stored on the database.当我使用
console.log(this.data)
在控制台上打印客户端收到的 object 时,我得到undefined
,因此我无法访问data.body
来打印存储在数据库中的数据。 Printing server-side gets the correct json object.打印服务器端得到正确的 json object。
I'm sending the object using HTTP status 200. Forcing a Bad Request ( res.status(400).json(docs);
) will print correctly the json body inside an Error.我使用 HTTP 状态 200 发送 object。强制执行错误请求(
res.status(400).json(docs);
)将正确打印 Z466DEEC76ECDF5FCA6D38571F6324D54 正文中的 Z466DEEC76ECDF5FCA6D38571F6324D54。
client.ts客户端.ts
getEvents() {
return new Promise(resolve => {
this.http.get('http://www.mywebsite.com:8080/api/objects')
.pipe(map(data => { })).subscribe(data => {
this.data = data;
console.log(this.data);
});
});
}
server.js服务器.js
app.get("/api/objects", function (req, res) {
db.collection(COLLECTION).find({})
.toArray(function (err, docs) {
if (err) {
handleError(res, err.message, "Failed.");
} else {
console.log(docs);
res.status(200).json(docs);
}
});
});
Make sure you're using some kind of body-parser, as the body-parser or express.json():确保您使用某种 body-parser,作为 body-parser 或 express.json():
app.use(express.json())
Put that before your routes!把它放在你的路线之前!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.