2016-09-19 46 views
1

我有一个快速的应用程序,它被设计成一个简单的restful api。 这是我的app.js文件中使用bodyparser 1.15.2表示意外的令牌k

增加身体解析器中间件

app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({extended: true})); 

这是我的基本的路由文件

... 
r.post('/search/:keyword', function(req, res){ 
var __keyword = req.params.keyword, 
console.log(req.body); 

我使用的邮差发送请求时,当我使用原始选项卡发送请求时,请求的结果是正确的。发送请求的这种方式生成的代码看起来像这样

POST /api/search/mykeyword HTTP/1.1 
Host: localhost:8080 
Content-Type: application/json 
Cache-Control: no-cache 
{ 
    "key": "value" 
} 

使用邮递员的X窗体-urlencoded选项时,我得到这个错误

SyntaxError: Unexpected token k 
    at parse (D:<projectpath>\node_modules\body-parser\lib\types\json.js:83:15) 
    at D:<projectpath>\node_modules\body-parser\lib\read.js:116:18 
    at invokeCallback (D:<projectpath>\node_modules\body-parser\node_modules\raw-body\index.js:262:16) 
    at done (D:<projectpath>\node_modules\body-parser\node_modules\raw-body\index.js:251:7) 
    at IncomingMessage.onEnd (D:<projectpath>\node_modules\body-parser\node_modules\raw-body\index.js:307:7) 
    at emitNone (events.js:67:13) 
    at IncomingMessage.emit (events.js:166:7) 
    at endReadableNT (_stream_readable.js:913:12) 
    at nextTickCallbackWith2Args (node.js:442:9) 
    at process._tickCallback (node.js:356:17) 

那么这个请求看起来像这样

POST /api/search/mykeyword HTTP/1.1 
Host: localhost:8080 
Content-Type: application/json 
Cache-Control: no-cache 

{ 
    "key": "value" 
} 

对我来说这看起来完全一样,但它产生这个错误?这是bodyparser,express或postman中的错误吗?或者这是我的错误? 当只调用

app.use(bodyParser.urlencoded({extended: true})); 

的req.body对象始终是空的,无论哪所描述的方法,我用

当您使用原始体
+0

我想你定身型为'X WWW的形式,urlencoded'和内容类型为'应用程序/ json'。您可以在标题中将Content-Type更改为'application/x-www-form-urlencoded'并检查? –

回答