【问题标题】:Find a right way to convert cURL to a POST request axios找到正确的方法将 cURL 转换为 POST 请求 axios
【发布时间】:2022-02-01 11:03:05
【问题描述】:

大家好,正如标题所说,我找不到解决方案。

这里是 cURL:

curl "https://test.api.amadeus.com/v1/security/oauth2/token" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}"

这是我从服务器收到 400 错误的代码:

const getToken = async () => {
try {
  const res = await axios.post(
    "https://test.api.amadeus.com/v1/security/oauth2/token",
    null,
    {
      params: {
        client_id: process.env.REACT_APP_AMADEUS_API_KEY,
        client_secret: process.env.REACT_APP_AMADEUS_SECRET_API_KEY,
        grant_type: "client_credentials",
      },
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    }
  );
  console.log(res);
} catch (error) {
  console.log(error);
}};

【问题讨论】:

标签: javascript reactjs api axios


【解决方案1】:

curl -d 以 application/x-www-form-urlencoded body 的形式发送数据。 axios.post 中的 params: 配置发送数据在查询字符串中。请改用data:,或仅在第二个参数中指定数据(替换您的null)。

【讨论】:

  • 这有助于解决请求,我已经使用code new URLSearchParams 作为正文,谢谢!
【解决方案2】:

axios post 方法应该有第二个参数作为主体参数,第三个参数作为配置对象,如标题。下面的代码可能会对你有所帮助。

const getToken = async () => {
try {
  const res = await axios.post(
    "https://test.api.amadeus.com/v1/security/oauth2/token",
    {
        client_id: process.env.REACT_APP_AMADEUS_API_KEY,
        client_secret: process.env.REACT_APP_AMADEUS_SECRET_API_KEY,
        grant_type: "client_credentials",
      },
    {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    }
  );
  console.log(res);
} catch (error) {
  console.log(error);
}};

【讨论】:

    猜你喜欢
    • 2021-11-12
    • 2020-02-26
    • 2021-02-14
    • 2019-08-17
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    相关资源
    最近更新 更多