【问题标题】:How to pass authentication token with every React request to back end API?如何将身份验证令牌与每个 React 请求一起传递给后端 API?
【发布时间】:2019-09-01 06:11:44
【问题描述】:

我有一个现有的应用程序,其中已经开发了 REST API。我正在考虑使用 React JS 开发前端,并且前端应该在每个请求中调用我的 REST API。

但是,当我登录到我的应用程序时,会生成一个令牌,该令牌会作为身份验证标头传递给每个后续请求。如何使用 React 实现这一目标? 我是 React 的初学者。

【问题讨论】:

  • 你如何通过你的 React 代码与 API 通信?

标签: reactjs


【解决方案1】:

您可以将axios 用作库,并将其添加为配置

axios.defaults.headers.common['Authorization'] = `Bearer ${token}` 

https://www.npmjs.com/package/axios

【讨论】:

    【解决方案2】:

    使用fetch。示例:

    var data = {myData: 'hello'}; // or just 'hello'
    
    fetch(YOUR_URL, {
      method: 'POST', // or GET
      body: JSON.stringify(data), // data can be string or object
      headers:{
        'Authorization': YOUR_TOKEN,
        // ... add other header lines like: 'Content-Type': 'application/json'
      }
    }).then(res => res.json()) // if response is json, for text use res.text()
    .then(response => console.log('Response:', JSON.stringify(response))) // if text, no need for JSON.stringify
    .catch(error => console.error('Error:', error));
    

    【讨论】:

      【解决方案3】:

      首先接收令牌并使用localStorage.setItem('token', JSON.stringify(userToken));将其保存到您的浏览器本地存储中

      然后,每次您发送请求时,您都会使用 localStorage.getItem("token") 从本地存储中获取此令牌

      此后,如果您要发布一个键值为 ID:1 的对象,您会这样做:

      await fetch("your_API_endpoint", {
                                  method: 'POST',
                                  headers: { 'Content-Type': 'application/json', "Authorization": localStorage.getItem("token")  },
                                  body: JSON.stringify({'ID': '1'})
                              })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-13
        • 2019-06-16
        • 1970-01-01
        • 2015-02-24
        • 2016-10-01
        • 2020-04-10
        • 1970-01-01
        • 2020-02-25
        相关资源
        最近更新 更多