Nodejs Express,Ajax 发布/jquery 并接收响应

发布于 2024-11-14 14:52:03 字数 927 浏览 0 评论 0原文

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

SyntaxError:意外的令牌非法 解析时(本地) 在传入消息。

在我的 Express 应用程序中,我有:

    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() {
      //called when complete
      console.log('process complete');
    },

    success: function(data) {
      console.log(data);
      console.log('process sucess');
   },

    error: function() {
      console.log('process error');
    },
  });

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

少女的英雄梦 2024-11-21 14:52:03

您没有发送有效的 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() 为我们完成了这个任务。

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.

海之角 2024-11-21 14:52:03

博恩斯牧师的评论对我来说特别重要,因为我正在使用 $.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;
} 

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

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

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]);
            // ...
        }
    }
    // ...
}

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:

// 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.

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]);
            // ...
        }
    }
    // ...
}
﹂绝世的画 2024-11-21 14:52:03

由于您使用的是express,

res.contentType('json');

应该是:

res.type('json');

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

请参阅有关 res.type 的express api 文档

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

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

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.

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.send and, while you are at it, res.json which 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.

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文