首页 > express4.x 框架 req.body获取不到前台post数据

express4.x 框架 req.body获取不到前台post数据

var option={
    type:"POST",
    url:"/",
    contentType:"application /json;charset:utf-8",
    dataType:"json",
    data:{
        ok:"on",
        temperature:"18",
    }
    success:function(response){
        console.log(response);
    }
    error:function(err){
        alert(err);
        }
    }
$.ajax(option);

以上是前台代码。。

app.post("/",function(req,res){
    var data={
        ok:req.body.ok,
        temperature:req.body.temperature
    }
    console.log(data);  
})

最后输出的为{ok:undefined,temperature:undefined}

我使用的express框架.

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

使用的bodyParser解析的模块。但是依然解析不到req.body里面的值。


没有区别!$.post() 是对$.ajax的封装而已


刚才换了一种ajax方式。。

使用

$.post("/",{ok:"on",temperature:"18"},function(data){
    //do something
})

这种方式是可以将数据传到后台的。 那么请问$.ajax() 和 $.post() 向node.js后台传送数据有什么区别呢?


contentType那一句画蛇添足了,本来默认就是'application/x-www-form-urlencoded; charset=UTF-8',你这改成'application/json;charset:utf-8'反而不行了。


jquery的ajax方法里,设置contentType是用来设置请求的contentType,而请求的contentType只有3种:application/x-www-form-urlencoded(默认值)、multipart/form-data、text/plain,application/json一般会是响应的contentType,而在jquery的ajax方法里,要用dataType:'json',来把设置响应的contentType设置为json

【热门文章】
【热门文章】