如何在React中使用axios post方法通过标头发送令牌

时间:2019-12-02 09:42:31

标签: reactjs

在我的React应用中,我正在使用axios来执行REST api请求。

但是它无法与请求一起发送Authorization标头。

这是我的代码:

这是authentication.js

async login(data) {
        try {
            const res = await axios.post(`'http://localhost:5000'/api/login`, data);
            this.subject.next(true);
            return res;
        } catch (error) {
            throw error;
        }
    }

这是login.js

async handleSubmit(e) {
        e.preventDefault();
        try {
            const res = await auth.login(this.state.data);
            tokenService.saveToken(res.data.token);
            this.setState({});
            swal({
                title: "Good job!",
                text: "Login successfully!",
                icon: "success",
            });
        }
        catch (error) {
            swal({
                title: "incorrect or password!",
                text: "Login failed!",
                icon: "error",
            });
        }
    }

4 个答案:

答案 0 :(得分:1)

您可以使用Axios创建一个实例,并将传递给它的标头保存在本地存储中。然后,使用该实例进一步发出请求。这样,您不必在每个请求中都包含它。

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  headers: {'Authorization': bearer <TOKEN_FROM_LOCALSTORAGE>}
});

使用实例进行请求

instance.get("users")
      .then(res => {
        console.log(res);
        console.log(res.data);
      })

您可以使用该实例并根据您的实例对其进行自定义,以使代码不会重复。 For further reference

答案 1 :(得分:0)

将其存储在本地存储中,然后将其与'Bearer'连接起来

SET NOCOUNT ON;
GO

IF (OBJECT_ID( N'[dbo].[GETNEXTGUID]') IS NOT Null)
    DROP PROCEDURE [dbo].[GETNEXTGUID];
GO

CREATE PROCEDURE [dbo].[GETNEXTGUID]
    (@NextId1 UNIQUEIDENTIFIER OUTPUT,
     @NextId2 UNIQUEIDENTIFIER OUTPUT)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @Sequence1 TABLE ([KEY] UNIQUEIDENTIFIER NOT NULL DEFAULT NEWSEQUENTIALID(), [DUMMY] BIT);
    DECLARE @Sequence2 TABLE ([KEY] UNIQUEIDENTIFIER NOT NULL DEFAULT NEWSEQUENTIALID(), [DUMMY] BIT);

    INSERT INTO @Sequence1 ([DUMMY]) VALUES (0);
    INSERT INTO @Sequence2 ([DUMMY]) VALUES (0);

    SELECT @NextId1 = [KEY] FROM @Sequence1;
    SELECT @NextId2 = [KEY] FROM @Sequence2;
END
GO

DECLARE @NextId1 UNIQUEIDENTIFIER;
DECLARE @NextId2 UNIQUEIDENTIFIER;

EXECUTE [dbo].[GETNEXTGUID] @NextId1 OUTPUT, @NextId2 OUTPUT;
PRINT @NextId1; PRINT @NextId2;

EXECUTE [dbo].[GETNEXTGUID] @NextId1 OUTPUT, @NextId2 OUTPUT;
PRINT @NextId1; PRINT @NextId2;

EXECUTE [dbo].[GETNEXTGUID] @NextId1 OUTPUT, @NextId2 OUTPUT;
PRINT @NextId1; PRINT @NextId2;

EXECUTE [dbo].[GETNEXTGUID] @NextId1 OUTPUT, @NextId2 OUTPUT;
PRINT @NextId1; PRINT @NextId2;

EXECUTE [dbo].[GETNEXTGUID] @NextId1 OUTPUT, @NextId2 OUTPUT;
PRINT @NextId1; PRINT @NextId2;

答案 2 :(得分:0)

检查用户是否通过身份验证以使用他们提出的“获取”或“发布”请求

isAuthenticated() {
    const token = localStorage.getItem('token');
  }

使用令牌发出发布请求

 axios({
        method: 'post',
        url: ''http://localhost:5000'/api/login',
        { headers: {"authorization" : token} }
        data: payload
        }),
        .then(response => response.json())
        .then(json => json)
        .catch(error => {
          throw error;
        });

处理您的登录信息

async handleSubmit(e) {
        e.preventDefault();
        try {
            const res = await auth.login(this.state.data);
            tokenService.saveToken(res.data.token);
            this.setState({});
            swal({
                title: "Good job!",
                text: "Login successfully!",
                icon: "success",
            });
        }
        catch (error) {
            swal({
                title: "incorrect or password!",
                text: "Login failed!",
                icon: "error",
            });
        }
    }

答案 3 :(得分:0)

为什么不使用像这样的axios拦截器:

axiosInstance.interceptors.request.use(
  config => {
    config.headers.authorization = localStorage.getItem("token");
    return config;
  },
  error => Promise.reject(error)
);

或在https://github.com/axios/axios/issues/1383上声明