jQuery POST to Node.JS Fails

jQuery POST to Node.JS Fails

本文关键字:JS Fails Node to POST jQuery      更新时间:2023-09-26

我试图通过熟悉node来扩大我的视野.js(我的职业是.NET开发人员),并且我在我认为是一个简单的POST示例时遇到了麻烦。我确实有jQuery的经验,所以node.js是我正在构建的这个示例网站中相对未知的一个。

节点.JS服务器代码:

var express = require('express');
var app = express();
app.configure(function() {
    app.use(express.bodyParser());
    app.use(app.router);
    app.use(express.logger());
});
app.use(express.static(__dirname + '/public/PRB_Presentation'));
app.post('/GetPage', function(request, response){
    console.log(request.body.pageNumber);
    response.send(request.body.pageNumber);
});
var port = 80;
app.listen(port);
console.log('Listening on port: ' + port);

我的客户端jQuery逻辑:

function getPage(pageNumber){
        $.ajax({
            url: '/GetPage',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: JSON.stringify({ pageNumber: pageNumber })
        }).done(function(data, textStatus, jqXHR) {
            console.log("Success: " + data);
        }).fail(function(jqXHR, textStatus, errorThrown) {
            console.log("Error: " + errorThrown);
        }).always(function() {
            console.log("Done!");
        })
        ;
    };

在我的 node.js 服务器运行时,我确实看到我发送的页码正确输出到控制台窗口,但这是我在客户端得到的:

错误:未知
做!

我想我在这里做一些非常简单的错误,但我不能完全弄清楚。

编辑

  • request.body.pageNumber 包含一个数字(例如,2)
  • fail() 中的文本状态只是"错误"

您收到错误的原因是因为您提供了 res.send() 中的数字。这样做会将值作为 HTTP 状态代码发送,而不是响应正文。

res.send(200);   -> HTTP 200 OK
res.send('200'); -> 200

send()方法接受两个参数。如果您提供一个并且它是一个数值,那么它将被解释为要发送的 HTTP 状态代码。您可能会发现更适合您正在尝试做的事情的是 res.json() .

app.post('/path', function(req, res) {
  res.json(request.body.page);
});

否则,强制将数字作为字符串发送:

app.post('/path', function(req, res) {
  res.send('' + request.body.page);
});