在node.js帖子中收到JSON对象是未定义的?

时间:2014-07-07 04:05:26

标签: javascript json node.js express centos

我有一个运行node.js http服务器的centOS服务器(参见下面的代码)我试图从命令行传递json:using

curl -X POST -H "application/json" -d '{"val1":"hello","val2":"my","val3":"world"}' localhost:3000/app1/webServ1

以下是node.js的代码:

    var http = require('http'),
    express = require('express'),
    path = require('path'),
    lower = require('./lower.js');



var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(express.static(path.join(__dirname, 'public')));


app.get('/', function (req, res)
{
    res.send('<html><body><h1>Hello World</h1></body></html>');
});

app.post('/:appName?/:webServ?', function (req,res) {

    var appName  = String(req.params.appName);
    var category = String(req.params.category);
    var webServ  = String(req.params.webServ);

    if ( (appName  == 'app1') && (webServ == 'webServ1') )
    {

        console.log("in webserv1 post");


         var address = req.body;
         console.log("Got request: " + JSON.stringify(address));

        console.log(address);  

        console.log(address.val1);
        console.log(address.val2);
        console.log(address.val3); 

       res.end();

    }
});

当我执行上述CURL命令时,为什么一直出现以下错误:

Got request: undefined
undefined
undefined
TypeError: Cannot read property 'val1' of undefined

1 个答案:

答案 0 :(得分:2)

您必须在问题中解决两件事

1) Express默认不解析请求正文。你必须使用中间件。

需要正文解析器

var bodyParser = require('body-parser');

在app.use行之前或之前添加这些行

app.use(bodyParser.json());
app.use(bodyParser.urlencoded());

如果您收到某些已弃用的警告urlencoded,请尝试使用

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

2)在您的CURL请求中,您未在Content-Type选项中指定-H属性

应该如下

 curl -X POST -H "Content-Type:application/json" -d '{"val1":"hello","val2":"my","val3":"world"}' localhost:3000/app1/webServ1