我正在測試發佈方法以創建待辦事宜項目,如下所示。我使用郵遞員在鉻模擬post方法調用。但是,它不起作用,並給我下面的錯誤。我懷疑body-parser庫的工作方式有問題。我在這裏做錯了什麼?使用快遞進行發佈時出錯JS
1 SyntaxError: Unexpected token b
2: at parse (/Users/zack/mydrive/proj/express-demo/node_modules/body-parser/lib/types/json.js:83:15)
3: at /Users/zack/mydrive/proj/express-demo/node_modules/body-parser/lib/read.js:116:18
4: at invokeCallback (/Users/zack/mydrive/proj/express-demo/node_modules/body-parser/node_modules/raw-body/index.js:262:16)
5: at done (/Users/zack/mydrive/proj/express-demo/node_modules/body-parser/node_modules/raw-body/index.js:251:7)
6: at IncomingMessage.onEnd (/Users/zack/mydrive/proj/express-demo/node_modules/body-parser/node_modules/raw-body/index.js:308:7)
7 at IncomingMessage.emit (events.js:104:17)
8 at _stream_readable.js:908:16
代碼:
var express = require('express');
var app = express();
var handlebars = require('express-handlebars');
var bodyParser = require('body-parser');
//MIDDLEWARE
app.engine('handlebars', handlebars({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}));
// TODOS
var todos = [
{ body: "take out the trash",completed: false},
{ body: "Do the laundry",completed:true},
{ body: "Make a screencast",completed:false}
]
app.post('/todos', function (req, res){
console.log("todo:", req.body);
var todo = req.body;
console.log("todo:"+todo);
todos.push(todo);
res.status(200).json(todo);
res.send('OK')
})
而且我觀察到的問題是,因爲這一行的。
app.use(bodyParser.json());
你在郵遞員發送的數據是什麼樣的? – tymeJV
確保您的數據是有效的JSON。我的猜測是你正在使用JavaScript語法。例如,JavaScript語法應該是'{bar:「baz」}「,但JSON需要引用鍵例如:」{「bar」:「baz」}'。 – mscdex
@tymeJV添加了郵差的截圖 – Zack