问题
I'm trying to do something very simple, I want to do a POST with AJAX Jquery to a Node.js server and have the server return a response. My problem is that I can't get that answer from the server. If someone can help me, I will be very grateful.
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);
});
回答1:
Try in server.js add CORS header, eg. like this
app.post('/vrp', function(req, res){
console.log(JSON.stringify(req.body));
res.header("Access-Control-Allow-Origin", "*").send(req.body);
});
If this run, then you have 100% sure that was CORS problem. For real app you can use this solution or more complex like middleware, eg.
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Or you can use cors middleware module https://github.com/expressjs/cors with more elastic configuration.
回答2:
app.post('/vrp', function(req, res){
console.log(JSON.stringify(req.body));
return res.status(200).send({data:req.body});
});
来源:https://stackoverflow.com/questions/49339446/post-with-jquery-and-receive-a-response-from-node-js