【问题标题】:axios content type not showing in requestaxios 内容类型未在请求中显示
【发布时间】:2020-06-16 07:30:32
【问题描述】:
var request = require('request');
var options = {
  'method': 'POST',
  'url': 'http://',
  'headers': {
  },
  form: {
    'username': '',
    'password': ''
  }
};
request(options, function (error, response) { 
  if (error) throw new Error(error);
  console.log(response.body);
});

将其转换为 axios 请求:

let data = qs.stringify({   'username': '',
'password': '' })
      const options = {
        method: 'POST',data,
        headers: {  'Content-Type': 'application/x-www-form-urlencoded'},        
        url: '',
      };

      response[0] = await Axios(options).then((res) => {
      console.log("res",res)
      return res.data
    }
    ).catch((err) => {
      console.log("err status", err.response.status)
      return err.response.data
    });

给出一个错误并且显示的标头没有编码的 url:

   url: '',
    method: 'post',
    data: 'username=&password=',
    headers: {
      Accept: 'application/json, text/plain, */*',
      'User-Agent': 'axios/0.19.2'
    },

为什么 content-type : url-encoded 不在标题中,只有 Accept: 'application/json, text/plain, /' 显示。

【问题讨论】:

    标签: node.js request axios fetch


    【解决方案1】:

    您没有显示您收到的错误,但您设置 Axios 调用的方式似乎与 Axios documentation 一致。所以我怀疑这是你如何设置 Node.js 服务器的问题。

    如果您使用的是 Express.js v.4+,可能您忘记在服务器中设置解析 application/x-www-form-urlencoded 内容类型的指令,如官方文档中的 here 所述。

    app.use(express.urlencoded({ extended: true }))
    

    如果您使用的是body-parser 软件包,您需要设置您的服务器:

    app.use(bodyParser.urlencoded({extended: true}));
    

    【讨论】:

    • 第一个工作的请求 (var request = require('request');),是 url 编码的请求吗??
    • request 是一个开箱即用支持 application/x-www-form-urlencoded 内容类型的 HTTP 客户端。如果之前的调用在您的服务器中正常工作,那么您可能在 Axios HTTP 客户端中的默认设置存在问题。检查您是否以任何方式使用拦截器。
    猜你喜欢
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 2016-04-08
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多