Axios等效于curl [英] Axios equivalent of curl

查看:168
本文介绍了Axios等效于curl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(nodeJS)axios等效于什么:

What is the (nodeJS) axios equivalent of:

curl --location --request POST '<URL>' \
--header 'API-Authorization: <KEY>' \
--form 'quantity=1' \
--form 'offset=0'

尝试:

const FormData = require('form-data')
const data = new FormData()
data.append('quantity', '1')
data.append('offset', '0')

axios({
  url: <URL>,
  method: 'POST',
  data,
  headers: {
    'API-Authorization': <KEY>
  }
})

但是服务器会提供500

But the server gives 500

推荐答案

与CURL请求代码等效的NodeJS应该是这样的:

The NodeJS equivalent of your CURL request code should be something like this:

const axios = require('axios');
const qs = require('qs');

let data = qs.stringify({ 'quantity': '1', 'offset': '0'});
let config = {
    method: 'post',
    url: 'https://someurl.com',
    headers: { 
        'API-Authorization': '<key>', 
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    data : data
};

axios(config)
.then((response) => {
    console.log(JSON.stringify(response.data));
})
.catch((error) => {
    console.log(error);
});

您需要的是 qs (QueryString)软件包,只需通过 npm install qs 进行安装即可.我只是通过在邮递员中生成请求来获得此输出的.

What you need for this is the qs (QueryString) package, simply install it by npm install qs. I got this output simply by generating the request in Postman.

这篇关于Axios等效于curl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆