[英]jQuery POST to Node.JS Fails
I'm trying to expand my horizons by getting familiar with node.js (I'm a .NET developer by profession), and I'm having trouble with what I assumed would be a simple POST example. 我正在尝试通过熟悉node.js(我是一个.NET开发人员)来扩大视野,并且遇到一些我认为简单的POST示例的问题。 I do have experience with jQuery, so node.js is the one relative unknown for me in this sample website I'm building.
我确实有使用jQuery的经验,所以在我正在构建的此示例网站中,node.js对我来说是一个相对未知的地方。
The node.JS server code: node.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);
My client-side jQuery logic: 我的客户端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!");
})
;
};
With my node.js server running, I do see the page number I send getting output to the console window correctly, but this is what I'm getting client-side: 在我的node.js服务器运行的情况下,我确实看到发送给控制台窗口的页码,但正确的是,这就是客户端的内容:
Error: unknown
错误:未知
Done!完成!
I assume I am doing something incredibly simple wrong here, but I can't quite figure it out. 我认为我在这里做的事情非常简单,但我无法弄清楚。
EDIT 编辑
The reason you're getting an error is because you're supplying a number in res.send()
. 出现错误的原因是因为您在
res.send()
提供了一个数字。 Doing so sends the value as the HTTP status code, rather than the response body. 这样做会将值作为HTTP状态代码发送,而不是发送响应正文。
res.send(200); -> HTTP 200 OK
res.send('200'); -> 200
The send()
method accepts two arguments. send()
方法接受两个参数。 If you supply one and it's a numerical value, then it will be interpreted as the HTTP status code to send. 如果您提供一个并且它是一个数字值,那么它将被解释为要发送的HTTP状态代码。 What you might find more applicable to what you're trying to do is
res.json()
. 您可能会发现更适合您要执行的操作是
res.json()
。
app.post('/path', function(req, res) {
res.json(request.body.page);
});
Otherwise, force the number to be sent as a string: 否则,强制将数字作为字符串发送:
app.post('/path', function(req, res) {
res.send('' + request.body.page);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.