[英]How to parse request body into JSON using Express
我的快遞應用程序中有以下設置:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
// Automatically parse request bodies
app.use(bodyParser.json());
// Automatically allow cross-origin requests
app.use(cors({ origin: true }));
app.post('/', (request, response) => {
// var message = request.body.message;
// message.sent_by_admin = true;
// The above two lines create an error.
console.log(request.body);
}
我從兩個注釋掉的行中得到的錯誤是這樣的:
TypeError: Cannot set property 'sent_by_admin' of undefined
當我打印request.body
,我在控制台中獲得以下內容:
{ '{\n "message": {\n "text": "hello"\n },\n "recipient": {\n "id": "123"\n },\n "sender": {\n "id": "456"\n },\n "timestamp": 1557949612342\n}': '' }
我發送的JSON是這樣的:
{
"message": {
"text": "hello"
},
"recipient": {
"id": "123"
},
"sender": {
"id": "456"
},
"timestamp": 1557949612342
}
如何將我的request.body
轉換為適當的JSON,以便我可以向數據添加/刪除屬性並保存它? 謝謝你的幫助。
它看起來像你POST
-ing其中有換行符在它身體。 嘗試POST
更多壓縮版本。
{"message":{"text":"hello"},"recipient":{"id":"123"},"sender":{"id":"456"},"timestamp":1557949612342}
問題在於客戶端,它發送了我的服務器無法解析的損壞的JSON數據。 一旦我嘗試了Postman ,問題就消失了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.