weixin_33694172 2019-05-08 15:35 采纳率: 0%
浏览 52

Ajax发布空数据

I am trying to make an AJAX post to my Express API.

I am expecting {user:Todd} to be returned in my data object, however whenever i try to log the request body, the object shows as empty./

$.ajax({
  url: '/api/test',
  type: 'POST',
  data: ({user: "Todd"})
})

I always test my endpoints with cURL as well, and i remember that i needed to pass the header "Content-Type: application/json" for this to work in the past.

$.ajax({
  url: '/api/test',
  type: 'POST',
  data: ({user: "Todd"}),
  contentType: 'application/json'
})

I am listening for requests on my NodeJS server and the above request doesnt even touch my server, while the first one sends empty JSON.

I am officially confused! How can adding a header break my API like this?

Here is the simple source code to my API.

var express = require('express');
var bodyParser = require('body-parser')

let app = express();
let port = 3000

app.use(bodyParser.json({
        limit:'150mb'
}));

app.post('/api/test', function(req, res) {
        console.log(req)
        console.log(req.body)
});

app.listen(port, () => console.log(`App listening on port ${port}`));
  • 写回答

2条回答 默认 最新

  • ??yy 2019-05-09 12:00
    关注

    Try this inside your html script tag

    const apiHost = "http://localhost:3000";
    
     $.ajax({
        url: `${apiHost}/api/test`, //add full path of your host
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ //JSON data needs to be stringified before its sent through http.
          'user': 'hello'
        })
      })
    

    The reason your server is not receiving the req is because of blocked/restricted CORS .

    Cross-origin resource sharing is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served. A web page may freely embed cross-origin images, stylesheets, scripts, iframes, and videos. -Wikipedia

    So do a npm install --save cors and use the code below

    var express = require('express');
    var bodyParser = require('body-parser')
    var cors = require('cors');
    
    let app = express();
    let port = 3000
    
    app.use(cors()); // add cors to middleware
    
    app.use(bodyParser.json()); 
    // for parsing application/json which was stringified in the ajax front-end
    
    app.use(bodyParser.urlencoded({ extended: true }));
    app.get('/api/test', function (req, res) {
       res.send("<h1>WOrking</h1>")
    })
    
    app.post('/api/test', function (req, res) {
       console.log(req.body)
    });
    
    app.listen(port, () => console.log(`App listening on port ${port}`));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?