如何将 cURL 转换为 axios 请求

Mar*_*son 8 curl node.js 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
Run Code Online (Sandbox Code Playgroud)

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

我尝试了以下代码:

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();
Run Code Online (Sandbox Code Playgroud)

这失败了。错误 400。grant_type 是必需的。我试过把它作为参数,包含在 data: json block 中。我想不通!

Mar*_*son 5

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

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();
Run Code Online (Sandbox Code Playgroud)

  • 您在中间添加了 null。异步函数 testApi() { 尝试 { const b = wait axios.post("https://oauth.nzpost.co.nz/as/token.oauth2", null, { params: { client_id: "xxxxxxxxxxxxxxxxxxxxxxxxx", client_secret: “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”,grant_type:“client_credentials”}});} catch (错误) { console.log(错误); } } (2认同)

sud*_*oul 5

curl -d是一种更简短的说法curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d。即使未指定,它也是一个POST 请求!-X POST

因此,请确保将 Axios 请求配置为 POST 请求,同时确保数据经过 URL 编码,标Content-Type头设置为application/x-www-form-urlencoded. 例如...

const response = await axios({
  url: 'example.com',
  method: 'post',
  headers: {
    'Content-Type': 'application/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'
  })
};
Run Code Online (Sandbox Code Playgroud)