2016-03-02 49 views
0

我爲博客寫了一個簡單的rest api。我有以下代碼(主文件):NodeJS/Express:PUT和body parser,body object爲空

var port = process.env.PORT || 8080; 
var express = require('express'); 
var mongoose = require('mongoose'); 
var bodyParser = require('body-parser'); 
var database = require('./config/database'); 
var app = express(); 
mongoose.connect(database.url); 

app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({extended: true})); 
app.use(express.static('public')); 

mongoose.connection.once('open', function() { 
    console.log('database connection established'); 
}); 

// Routes 
app.use('/api/blog', require('./routes/blogroutes.js').router); 

// Start 
app.listen(port, function() { 
    console.log('listening on port ', port); 
}); 

文件blogroutes.js如下所示(摘錄):

var express = require('express'); 
var router = express.Router(); 

var BlogEntry = require('../models/blogEntry'); 

router.use(function (req, res, next) { 
    next(); 
}); 

router.route('/entry/:year/:month/:day/:nr') 
    //.get(...).delete(...) 
    .put(function (req, res) { 
     console.log(req.body); 
    }); 

router.post('/entry', function (req, res) { 
    console.log(req.body); 
}); 

module.exports = {router: router}; 

現在的問題是:當我在PowerShell中curl -uri http://localhost:8080/api/blog/entry/2016/3/2/3 -method put -body @{title='my first entry';text='Lorem ipsum'}打電話,控制檯輸出是{}。當我調用PowerShell curl -uri http://localhost:8080/api/blog/entry -method post -body @{title='my first entry';text='Lorem ipsum'}時,控制檯輸出與預期的一樣{ text: 'Wonderful', title: 'My second bike trip' }。你有什麼想法爲什麼以及如何訪問put body?

+1

您是否嘗試在您的'PUT'路由處理程序中添加'console.log(req.headers ['content-type'])'來查看正在發送什麼'Content-Type'? – mscdex

+0

將'-H「Content-Type:application/json」'添加到您的服務的'curl'調用中,查看是否修復了它 – peteb

+0

console.log(... content-type ...)返回undefined。 -H參數在此PowerShell命令中不起作用。 – Green

回答

1

由於它並不像你使用真正捲曲,而是它似乎像PowerShell的Invoke-WebRequest cmdlet時,the documentationInvoke-WebRequest特別提到的application/x-www-form-urlencodedContent-Type將只爲POST請求被髮送。因此,您需要通過指定附加的命令行選項-ContentType "application/x-www-form-urlencoded"來明確設置Content-Type以指示非請求。

+0

不錯!感謝您的洞察! :) – Green