我无法将数据发布到服务器并收到超时错误。请参见下面的代码:
$(document).ready(function(){
$('#form1').on('submit',function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/",
timeout: 2000,
data : JSON.stringify({ image: "yo", text: "apples" }),
dataType : 'json',
success: function(data) {
alert('Success!')
},
error: function(jqXHR, textStatus, err) {
alert('text status '+textStatus+', err '+err)
}
});
})
})
app.use(bodyParser.json());
app.post('/', function (req, res){
console.log(req.body);
console.log('req received');
});
在服务器上,我看到的输出为
APP STARTED ON PORT - 3000
{}
req received
您能为我为什么无法接收数据提供指导吗?预先谢谢你。
答案 0 :(得分:1)
超时的原因是您没有响应请求。即使您的api没有任何结果,您也应该至少使用状态码来响应请求。
res.sendStatus(200);
body-parser
默认仅解析content-type
为application/json
的请求。尝试将contentType: 'application/json; charset=UTF-8'
添加到jQuery ajax选项。
$.ajax({
...
contentType: 'application/json; charset=UTF-8',
...
});
答案 1 :(得分:0)
正文始终作为对象发送。...不要对其进行字符串化!