node路由
router.post('/',(req,res)=>{
console.log(req.body,1);
res.json({name:1,age:3})
});
javascript代码
function ajax(options){
let {url,success} = options,
type = options.type || 'GET',
data = options.data || null,
contentType = options.contentType || 'application/x-www-form-urlencoded';
let req = new XMLHttpRequest();
req.open(type,url,true);
if(/^POST$/i.test(type)) req.setRequestHeader('Content-Type',contentType);
req.onreadystatechange = function(){
console.log(req.status,req.readyState);
if(req.readyState === 4 && req.status === 200){
success && success(req.response);
}
}
req.send(data);
}
ajax({
url:'/aaa',
type:'post',
data:{"a":1,"b":2},
success:(data)=>{
console.log(data);
}
});
data
是 {"a":1,"b":2}
后台输出 { 'object Object': '' } 1
data
是 "abc"
后台输出 { abc: '' } 1
data
是
var formData = new FormData();
formData.append('a',1);
后台输出
{ '------WebKitFormBoundaryhR4KppDAZDAMRtnj\r\nContent-Disposition: form-data; name': '"a"\r\n\r\n1\r\n------WebKitFormBoundaryhR4KppDAZDAMRtnj--\r\n' } 1
这是什么问题?平常都是用的jquery的ajax传的没什么事。
后台向前台传数据可以正常接受
因为你最后数据没有进行序列化,比如把
{"a":1,"b":2}
转化为a=1&b=2
这种形式。ajax不能直接传递json,需要进行先转化为字符串,然后后端接受后再转换为json