首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将cURL转换为axios请求

如何将cURL转换为axios请求
EN

Stack Overflow用户
提问于 2019-03-27 12:51:02
回答 2查看 17.5K关注 0票数 8

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

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

代码语言:javascript
复制
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

这工作得很好(当我输入我的凭证时)

我尝试了以下代码:

代码语言:javascript
复制
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块中。我搞不懂这事!

EN

回答 2

Stack Overflow用户

发布于 2019-03-27 13:52:41

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

代码语言:javascript
复制
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();
票数 5
EN

Stack Overflow用户

发布于 2020-11-10 15:27:19

提醒一下,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。例如..。

代码语言:javascript
复制
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'
  })
};
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55370000

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档