最近刚开始接触node.js,想用restify开发接口,但是一直都获取不到post提交的数据。
部分代码如下: server.use(restify.acceptParser(server.acceptable)); server.use(restify.bodyParser()); server.use(restify.urlEncodedBodyParser()); server.use(restify.queryParser());
var name = req.body.name; console.log("name = " + name); //name一直都是undefined
请求: curl -i -X POST -d name=’jason’ http://127.0.0.1:8899/test
请各位同学帮忙指点一下!
req不是undefined,如下:
POST /test HTTP/1.1 user-agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2 host: 127.0.0.1:8899 accept: / content-length: 10 content-type: application/x-www-form-urlencoded
console.log("body: %s", JSON.stringify(req.body));
console.log("params: %s", JSON.stringify(req.params));
打印body和params如下:
body: undefined params: {}
完整代码:
var restify = require(‘restify’);
var server = restify.createServer({ name:’myApp’ });
function postRespond(req,res,next){ console.log("执行到postRespond方法中 req = " + req);
console.log("body: %s", req.body);
console.log("params: %s", JSON.stringify(req.params));
console.log("name = " + req.body.name);
res.send(201, Math.random().toString(36).substr(3, 8));
return next();
}
var postServerPath = '/hello’; server.post(postServerPath,postRespond);
console.log(“client.connect OK.\n”);
server.use(restify.pre.userAgentConnection()); server.use(restify.acceptParser(server.acceptable)); server.use(restify.queryParser()); server.use(restify.urlEncodedBodyParser()); server.use(restify.bodyParser());
var ip_addr = '127.0.0.1’; var port = '8899’; server.listen(port,ip_addr, function() { console.log('%s listening at %s’, server.name, server.url); });
输出: body: undefined params: {}
请求: curl -i -X POST -d “name=jason” http://127.0.0.1:8899/hello 返回: {"code":"InternalError","message":"Cannot read property ‘name’ of undefined"}