【发布时间】:2018-03-17 16:51:53
【问题描述】:
我正在尝试做一些非常简单的事情,我想使用 AJAX Jquery 对 Node.js 服务器进行 POST 并让服务器返回响应。我的问题是我无法从服务器获得答案。如果有人可以帮助我,我将非常感激。
client.js
$(document).ready(function(){
$("button").click(function(){
$.post("http://localhost:3333/vrp",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status); //This section code doesn't execute.
})
.fail(function() {
alert( "error" ); //It's executed this section of code and I can see it in my browser.
});
});
});
server.js
var vrp = require("./vrp");
var bodyParser = require("body-parser");
var express = require('express');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/vrp', function(req, res){
console.log(JSON.stringify(req.body)); //Here I can see the message I sent.
res.contentType('json');
res.send(JSON.stringify(req.body));
});
var listener = app.listen(3333, function () {
console.log('Your app is listening on port ' +
listener.address().port);
});
【问题讨论】:
-
您收到什么错误消息 - 请检查您的浏览器开发工具?这可能是与 CORS 相关的问题...
-
你试过
contentType('jsonp')吗? -
也许你不需要这个:
res.contentType('json'); res.send(JSON.stringify(req.body));它res.send(req.body);应该足够了 -
我将尝试@Oliver 告诉我的解决方案,其他人的解决方案不起作用(我认为可能是配置问题)。如何查看响应的错误消息?很抱歉这个问题,我是这方面的初学者,我不太了解。
-
看我的回答,它有一些准备测试/准备使用的代码。