一条小码农

努力一点,现在想要的未来都会有。

process 请求数据解析问题

开发过程中发现ajax提交的数据无法被express正确的解析,主要的情况是这样的:

  1. // 浏览器端post一个对象
  2. $.ajax({
  3. url:"/save",
  4. type:"post",
  5. data:{
  6. name:"henry",
  7. age:30,
  8. hobby:["sport","coding"]
  9. }
  10. });
  11. // express接收这个对象
  12. router.post("/save",function(req, res, next){
  13. console.log(req.body);// => { 'info[name]': 'henry','info[age]': '30','hobby[1]': 'sport','hobby[2]': 'coding' }
  14. });

解决方式:

使用bodyParser中间件

bodyParser中间件用来解析http请求体,是express默认使用的中间件之一。

使用express应用生成器生成一个网站,它默认已经使用了 bodyParser.json 与 bodyParser.urlencoded 的解析功能,除了这两个,bodyParser还支持对text、raw的解析。

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

顾名思义,bodyParser.json是用来解析json数据格式的。bodyParser.urlencoded则是用来解析我们通常的form表单提交的数据,也就是请求头中包含这样的信息:





posted @ 2017-07-19 14:56  萝卜的博  阅读(240)  评论(0编辑  收藏  举报