【问题标题】:How to add a BearerToken to React API Requests?如何将 BearerToken 添加到 React API 请求?
【发布时间】:2017-06-05 02:37:30
【问题描述】:

React 新手寻求帮助...我正在使用 React 发出 API 请求,如下所示:

class CatsApi {
  static createCat(cat) {
    const request = new Request('http://localhost:4300/api/v1/cats', {
      method: 'POST',
      headers: new Headers({
        'Content-Type': 'application/json'
      }),
      body: JSON.stringify(cat)
    });

    return fetch(request).then(response => {
      return response.json();
    }).catch(error => {
      return error;
    });
  }

同时,我通过 react-devise 对我的 API 进行了身份验证: https://github.com/timscott/react-devise 其中有一个方法getBearerToken 像这样:https://github.com/timscott/react-devise/blob/master/src/actions/authTokenStore.js

如何使用 getBearerToken 向 API 传递令牌,以便 API 请求使用令牌进行身份验证?

谢谢!

【问题讨论】:

    标签: ruby-on-rails reactjs oauth ruby-on-rails-5


    【解决方案1】:

    您可以使用Authorization 标头,例如:

    { 'Authorization': `Bearer ${authToken}` }
    

    使用fetch,您可以尝试以下方式:

    fetch('http://localhost:4300/api/v1/cats', {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${token}`
            'Accept'       : 'application/json',
            'Content-Type' : 'application/json',
        },
        body: JSON.stringify({
            cat : cat_value,
        })
    })
    .then((response) => response.json())
    .then((responseData) => { console.log(responseData) })
    .catch((error) => { console.log(error) })
    .done()
    

    此外,如果您在发出请求时可以在控制台或浏览器控制台中查看 Rails 输出,那将是非常棒的。

    【讨论】:

    • 非常感谢您的回复。我是一个新手,根据上面提供的代码,是否可以更详细地展示我将如何完成这项工作?我尝试了您提供的内容,但没有成功。
    • 上面的 ${token} 是如何被填充的?
    • 在网络监视器中,它实际上是在发送Bearer ${token} --- 应该填充令牌吗?
    • 是的,无论您使用何种方式获取令牌,您都需要获取令牌,如果您使用 React,它可以存储在 SessionStorage 中。
    猜你喜欢
    • 2017-01-16
    • 2017-08-18
    • 2015-09-15
    • 2011-10-14
    • 1970-01-01
    • 2011-12-11
    • 2018-11-29
    • 1970-01-01
    • 2021-08-15
    相关资源
    最近更新 更多