【问题标题】:Axios POST data does not send in correct format to Express ServerAxios POST 数据未以正确格式发送到 Express Server
【发布时间】:2022-10-07 21:15:47
【问题描述】:

嗨,我正在运行一个快速服务器,它在/ 上路由了这个.post,并使用Formidableexpress.json() 作为中间件。

快递服务器

const formidable = require('express-formidable');
app.use(express.json());
app.use(formidable());

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

使用 AJAX(没有问题)

当我使用 AJAX 发送 POST 请求时,如下所示:

$.ajax({
  url:'http://localhost:3000/test',
  type: "POST",
  crossDomain: true,
  dataType: "json",
  data: {
    "file" : "background.js"
  },
  success: async function (response) {
  }
})

服务器输出:

{ file: 'background.js' }

问题

但是,当我使用 AXIOS 发送相同的 POST 请求时

var fUrl = 'http://localhost:3000/test';
var fHeader = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
};
var req = await axios({
    method: "POST",
    url: fUrl,
    withCredentials: true,
    data: {"file" : 'background.js'},
    headers: fHeader
});

服务器以错误的格式输出:

{ '{"file":"background.js"}': '' }

我怀疑这个问题可能是因为content-type 标头,但是当我将其更改为application/json 时,请求没有完成/超时和awaits 显然是无限的时间。

【问题讨论】:

    标签: node.js express axios formidable


    【解决方案1】:
    app.use(express.json());
    app.use(formidable());
    

    切勿同时使用两者。

    这也不是发送文件的方式,但这将是另一个问答

    【讨论】:

      猜你喜欢
      • 2016-11-21
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 2020-11-10
      • 2012-02-11
      • 2019-06-20
      • 2019-03-04
      • 1970-01-01
      相关资源
      最近更新 更多