【问题标题】:Ajax Requests FailingAjax 请求失败
【发布时间】:2017-04-02 16:29:34
【问题描述】:

Post 请求保持等待状态。 我想记录传入请求的 JSON 正文。 使用 Postman 时请求有效,但 AJAX 请求无效

节点代码:

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 请求

    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)
  });

【问题讨论】:

  • 为什么不起作用?肯定有错误或某些指标。
  • 请求总是处于待处理状态,不知道为什么
  • 以及节点内的哪些函数以什么顺序被调用?
  • 全部然后发布?
  • 这是猜测吗?还是您打开了调试器。因为如果这两个回调都被调用了,它就不会仍然处于挂起状态。

标签: javascript jquery ajax node.js express


【解决方案1】:

我认为您没有使用 jQuery 处理 ajax 调用的响应。您正在发送数据,但我没有看到您收到服务器响应。 POSTMAN 会自动为您处理。

【讨论】:

  • 这似乎不是问题。
【解决方案2】:

这是一个与 CORS 相关的问题。前面通过在同一个 IP 地址上启动前端和后端来解决。

【讨论】:

    猜你喜欢
    • 2018-11-30
    • 2013-01-15
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    相关资源
    最近更新 更多