javascript - 如何将身份验证 header 传递给其他组件

标签 javascript reactjs authentication axios

所以我最近开始使用 React,我正在我的应用程序组件中对用户进行身份验证,如下所示:

应用程序

signIn(userData) { 
  console.log(userData)
  //do a fetch call to get/users
  axios.get('http://localhost:5000/api/users', {
   auth: { //set auth headers so that userData will hold the email address and password for the authenticated user 
       username: userData. emailAddress,
       password: userData.password

}
}).then(results => { console.log(results.data)
      this.setState({
        //set the authenticated user info into state
        emailAddress: results.data,
        password: results.data.user
      });
})

}

我还有另一个名为 CreateCourse 的组件,仅当我从应用程序提供身份验证 header 时才允许发布请求,

创建类(class)

 handleSubmit = event => {
          event.preventDefault();
          console.log(this.props)
          const newCourse = {
            title: this.state.title,
            description: this.state.description,
            estimatedTime: this.state.estimatedTime,
            materialsNeeded: this.state.materialsNeeded
          };
          axios({ 
            method: 'post',
            url: 'http://localhost:5000/api/courses',
            auth: {
              username: this.props.emailAddress,
              password: this.props.password
           },
            data: newCourse
            }).then(
              alert('The course has been successfully created!')
            ).then( () => {
              const {  history } = this.props;
              history.push(`/`)
            })
        };

我想知道是否可以在不使用 props 或 context api 的情况下将 auth header 从 App 传递到子组件,这样我就不必在每个 axios 请求上手动放置 auth header ,以供引用,这是我的存储库: https://github.com/SpaceXar20/full_stack_app_with_react_and_a_rest_api_p10

最佳答案

我总是创建一个单例 axios 实例并在用户登录成功后为其设置 header 。

let instance = null

class API {
  constructor() {
    if (!instance) {
      instance = this
    }
    this.request = Axios.create({
      baseURL: 'http://localhost:5000',
    })
    return instance
  }

  setToken = (accessToken) => {
    this.request.defaults.headers.common.authorization = `Bearer ${accessToken}`
  }

  createCourses = () => this.request.post(...your post request...)
}

export default new API()

登录成功后,需要调用API.setToken(token)。然后,当您调用 Api.createCourse() 时,请求 header 中将包含 token 。

关于javascript - 如何将身份验证 header 传递给其他组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55192985/

相关文章:

javascript - 在 JSON 中查找一组对象

javascript - onclick 将值推送到数组并循环以添加数组值。 JavaScript

javascript - 自定义滚动条

reactjs - 如何在 useCallback 中使用全局对象而不将其作为依赖项(删除警告)

javascript - Mongodb 字符串匹配正则表达式

javascript - 如何使用钩子(Hook)更改数组的状态?

javascript - 如何动态解构一个巨大的 JSON 对象?

ruby-on-rails - 登录或注册后,如何使Devise重定向到存储的位置?

javascript - 以编程方式在 UIWebview 中填充数据

c# - 如何获取远程登录用户的 WindowsIdentity?