[英]Ajax Requests Failing
The Post requests stay pending. Post 请求保持未决状态。 I wanted to log the JSON body of the incoming request.我想记录传入请求的 JSON 正文。 The request works when using Postman but the AJAX requests dont work使用 Postman 时请求有效,但 AJAX 请求无效
Node Code:节点代码:
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var hostname = 'localhost';
var port = 3000;
var app = express();
app.use(morgan('dev'));
var qRouter = express.Router();
qRouter.use(bodyParser.json());
qRouter.route('/')
.all(function(req,res,next) {
res.header('Access-Control-Allow-Origin', "*")
res.writeHead(200, { 'Content-Type': 'application/json' });
next();
})
.post(function(req,res){
console.log(req.body);
res.end("lalal");
})
app.use('/play',qRouter);
app.listen(port, hostname, function(){
console.log(`Server running at http://${hostname}:${port}/`);
});
AJAX REQUEST AJAX 请求
var d = {
"rating": 5,
"comment": "Sends anyone to heaven, I wish I could get my mother-in-law to eat it!",
"author": "Paul McVites"
}
$.ajax({
url: 'http://localhost:3000/play',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(d)
});
I think you are not handling your the response of your ajax call with jQuery.我认为您没有使用 jQuery 处理 ajax 调用的响应。 You are sending the data, but I don't see you receiving the server response.您正在发送数据,但我没有看到您收到服务器响应。 POSTMAN handles this automatically for you. POSTMAN 会自动为您处理。
This was a CORS-related issue.这是一个与 CORS 相关的问题。 Solved earlier by starting the frontend and backend on the same IP address.之前通过在相同的 IP 地址上启动前端和后端来解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.