如何将cURL转换为axios请求

时间:2019-03-27 04:51:02

标签: node.js curl axios

我显然在这里忽略了一些东西

我正在尝试将cURL请求从Here转换为axios。

curl -d "grant_type=client_credentials\
&client_id={YOUR APPLICATION'S CLIENT_ID} \
&client_secret={YOUR APPLICATION'S CLIENT_SECRET}" \
https://oauth.nzpost.co.nz/as/token.oauth2

这很好(当我输入凭据时)

我尝试了以下代码:

import axios from "axios";

async function testApi() {
  try {
    const b = await axios.post("https://oauth.nzpost.co.nz/as/token.oauth2", {
      client_id: "xxxxxxxxxxxxxxxxxxxxxxxxx",
      client_secret: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
      grant_type: "client_credentials"
    });
  } catch (error) {
    console.log(error);
  }
}

testApi();

这失败。错误400。必须是grant_type。我已经尝试将其作为参数包含在data:json块中。我无法弄清楚!

2 个答案:

答案 0 :(得分:0)

我修复了它,我需要将值放在参数中

import axios from "axios";

async function testApi() {
  try {
    const b = await axios.post("https://oauth.nzpost.co.nz/as/token.oauth2",
        params: {
          client_id: "xxxxxxxxxxxxxxxxxxxxxxxxx",
          client_secret: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
          grant_type: "client_credentials"
        });
  } catch (error) {
    console.log(error);
  }
}

testApi();

答案 1 :(得分:0)

提醒一下,curl -d只是curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d的简短表达。即使未指定-X POST,它也是 POST请求

因此,您可以将axios请求配置为POST请求,同时还要确保将{strong>数据进行了URL编码,并且将Content-Type标头设置为application/x-www-form-urlencoded。例如...

const response = await axios({
  url: 'example.com',
  method: 'post',
  headers: {
    'Content-Type': 'x-www-form-urlencoded'
  },
  // For Basic Authorization (curl -u), set via auth:
  auth: {
    username: 'myClientId',
    password: 'myClientSecret'
  },
  // This will urlencode the data correctly:
  data: new URLSearchParams({
    grant_type: 'client_credentials'
  })
};

 
相关问题