restify框架获取post数据
发布于 18天前 作者 yaoqinzhou 288 次浏览 来自 问答

最近刚开始接触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

请各位同学帮忙指点一下!

9 回复

你这段代码,是不是连req都是undefined~

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: {}

如果把url改成 ‘/test/:name’ 通过 req.params.name; 能获取数据

哪位同学能指点下?

listen在哪? 来点完整代码.

完整代码:

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"}

哪位同学能指点下?

是太肤浅了吗? 没人愿意指点下???

回到顶部