【问题标题】:NodeJS/Express: PUT and body parser, body object emptyNodeJS/Express:PUT 和 body 解析器,body 对象为空
【发布时间】:2016-03-02 20:17:23
【问题描述】:

我为博客写了一个简单的rest api。我有以下代码(主文件):

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 正文吗?

【问题讨论】:

  • 您是否尝试在您的PUT 路由处理程序中添加console.log(req.headers['content-type']) 以查看Content-Type 正在发送什么?
  • -H "Content-Type: application/json" 添加到您的服务的curl 调用中,看看是否可以解决问题
  • console.log(...content-type...) 返回未定义。 -H 参数在此 PowerShell 命令中不起作用。

标签: node.js express put body-parser


【解决方案1】:

因为它看起来不像您在使用 real cURL,但它似乎类似于 Powershell 的 Invoke-WebRequest cmdlet,the documentation for Invoke-WebRequest 特别提到 @ application/x-www-form-urlencoded 中的 987654324@ 将仅针对 POST 请求发送。因此,您需要通过指定额外的命令行选项为非POST 请求显式设置Content-Type-ContentType "application/x-www-form-urlencoded"

【讨论】:

  • 不错!感谢您的洞察力! :)
猜你喜欢
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
  • 1970-01-01
  • 2016-07-25
  • 2017-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多