【问题标题】:How to do Basic Auth with Axios in react如何在反应中使用 Axios 进行基本身份验证
【发布时间】:2021-06-24 16:38:02
【问题描述】:

反应代码

import React, { useState, useEffect } from "react";
import axios from "axios";

const Table = () => {
  useEffect(() => {
    console.log("helllllllllllllllo");

    callAPI();
  }, []);

  const callAPI = async () => {
    const url =  "some URL";
    const password = "Secret" ;
    const username = "Consumer Key";

    const data = await axios.get(
      url,
      {},
      {
        auth: {
          username: username,
          password: password,
        },
      }
    );

    console.log("data", data);
  };
  return (
   <div> Hello </div>
  );
};

export default Table;


在 Postman 上,我转到 Authorization 选项卡并在各自的输入字段中输入用户名和密码并获得结果,但使用 axios,我收到 401 错误。 确切的错误是:-

createError.js:16 Uncaught (in promise) Error: Request failed with status code 401
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:62)

【问题讨论】:

    标签: reactjs api axios postman


    【解决方案1】:

    您错误地传递了身份验证标头。在 axios GET 中,第一个参数是 URL,第二个参数是 config 对象。在config 对象中,您可以提供auth 属性用于发送basic auth 标头。

    const data = await axios.get(url, {
      auth: {
        username: username,
        password: password,
      },
    })
    

    【讨论】:

      猜你喜欢
      • 2018-07-19
      • 2017-10-19
      • 2015-08-12
      • 2017-06-13
      • 2013-05-30
      • 2016-07-01
      • 2020-10-31
      • 2018-08-28
      • 2023-03-27
      相关资源
      最近更新 更多