nodejs express,ajax发布w / jquery和接收响应 [英] nodejs express, ajax posting w/ jquery and receiving response
问题描述
语法错误:意外的令牌ILLEGAL
在解析(本机)
在IncomingMessage。
在我的快速应用程序中,我有:
app.post('/ save ',function(req,res){
console.log(req.body.objectData);
res.contentType('json');
res.send({some:'json '});
});
和我的jquery:
$ .ajax({
url:/ save,
type:POST,
dataType:json,
data: {objectData:someObject},
contentType:application / json,
cache:false,
timeout:5000,
complete:function(){
//调用完成
console.log('process complete');
},
成功:function(data){
console.log(data);
console.log('process sucess');
},
错误:function(){
console.log('process error');
},
});
您没有发送有效的JSON响应,包含单词 json
因此,客户端的 JSON.parse()
失败。尝试这样:
app.post('/ save',function(req,res){
console.log (req.body.objectData);
res.contentType('json');
res.send({some:JSON.stringify({response:'json'})});
});
JavaScript对象符号是以对象格式在应用程序之间共享数据的方式。但是,您无法通过HTTP请求发送对象,而无需先将其转换为字符串并将其作为单个变量发送。函数 JSON.parse()
和 JSON.stringify()
为我们做这个。
Having some trouble getting express to respond properly to my jquery ajax request. The actual posting is working fine, but no matter what I try I cant seem to actually get a data response from my app that I can use. At first it was just posting and hanging constantly, and like a minute later it would respond with an alert that said something like "XML Document loaded" (have no idea where it was coming from) -- Anyways, now its giving me
SyntaxError: Unexpected token ILLEGAL at parse (native) at IncomingMessage.
In my express App, I have:
app.post('/save', function(req, res) {
console.log(req.body.objectData);
res.contentType('json');
res.send({ some: 'json' });
});
and in my jquery:
$.ajax({
url: "/save",
type: "POST",
dataType: "json",
data: {objectData: someObject},
contentType: "application/json",
cache: false,
timeout: 5000,
complete: function() {
//called when complete
console.log('process complete');
},
success: function(data) {
console.log(data);
console.log('process sucess');
},
error: function() {
console.log('process error');
},
});
You are not sending a valid JSON response but a String containing the word json
therefore the JSON.parse()
is failing on the client side. Try this:
app.post('/save', function(req, res) {
console.log(req.body.objectData);
res.contentType('json');
res.send({ some: JSON.stringify({response:'json'}) });
});
JavaScript Object Notation is a way to share data between applications in object format. However, you cannot send an object over an HTTP request without first turning it into a string and sending it as a single variable. The functions JSON.parse()
and JSON.stringify()
do this for us.
这篇关于nodejs express,ajax发布w / jquery和接收响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!