nodejs express,ajax 发布 w/jquery 并接收响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6289276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:38:35  来源:igfitidea点击:

nodejs express, ajax posting w/ jquery and receiving response

jqueryajaxnode.jsexpress

提问by thrice801

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

在快速响应我的 jquery ajax 请求时遇到了一些麻烦。实际发布工作正常,但无论我尝试什么,我似乎都无法从我可以使用的应用程序中实际获得数据响应。起初它只是不断地发布和挂起,就像一分钟后,它会响应一个警报,说“加载了 XML 文档”(不知道它来自哪里)——无论如何,现在它给了我

SyntaxError: Unexpected token ILLEGAL at parse (native) at IncomingMessage.

SyntaxError:在 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:

在我的 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');
    },
  });

回答by Pastor Bones

You are not sending a valid JSON response but a String containing the word jsontherefore the JSON.parse()is failing on the client side. Try this:

您发送的不是有效的 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 Object Notationis 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.

JavaScript Object Notation是一种以对象格式在应用程序之间共享数据的方法。但是,如果不先将对象转换为字符串并将其作为单个变量发送,则无法通过 HTTP 请求发送对象。函数JSON.parse()JSON.stringify()为我们执行此操作。

回答by CLO

Pastor Bones' comment was particularly important to me, as I was using $.ajax to post to a Node server. My relevant portion of code ended up like this:

Pastor Bones 的评论对我来说特别重要,因为我使用 $.ajax 发布到 Node 服务器。我的相关代码部分最终是这样的:

// Incoming parameter "teams" is an array of objects
function saveTeams(teams) {
    var xhr;
    var data = JSON.stringify({ teams: teams });

    xhr = $.ajax({
        type: "POST",
        url: "http://localhost:8000/saveteam",
        contentType: "application/json",
        data: data,
        headers: {
            Authorization: "..."
        }
    });

    return xhr;
} 

Note that the contentType header is relevant for the parsing to work.

请注意, contentType 标头与解析工作相关。

On the node server side, I can process the payload like this:

在节点服务器端,我可以像这样处理有效负载:

saveTeams: function (req, res, next) {
    var teams = req.body.teams;

    if (teams.length > 0) {
        console.log("Teams to be added:");
        for (var i = 0; i < teams.length; i++) {
            console.log(teams[i]);
            // ...
        }
    }
    // ...
}

回答by Montana123

Since you are using express,

由于您使用的是快递,

res.contentType('json');

should be:

应该:

res.type('json');

but setting the type is not required since it is done automatically for you.

但是不需要设置类型,因为它会自动为您完成。

See the express api docs on res.type.

请参阅res.type 上express api 文档

Also note that, for express, res.send({blah:"gee"});automatically converts json objects using JSON.stringify internally. After clicking the above link, click on res.sendand, while you are at it, res.jsonwhich saves a little processor overhead when you know you are sending JSON. Note that if you send JSON, the type is automatically set to JSON.

另请注意,对于 express,在res.send({blah:"gee"});内部使用 JSON.stringify 自动转换 json 对象。点击上面的链接后,点击res.sendand,当你在它的时候,res.json当你知道你正在发送 JSON 时,它会节省一点处理器开销。请注意,如果您发送 JSON,则类型会自动设置为 JSON。

Always best to look at the source! Note that res.send calls this.json when it detects JSON, and that res.json calls this.send (yeah seems like a loop but it all works out).

最好还是看源码!请注意, res.send 在检测到 JSON 时调用 this.json,而 res.json 调用 this.send(是的,看起来像一个循环,但一切正常)。