繁体   English   中英

如何将身份验证标头传递给其他组件

[英]How can I pass auth headers to other components

所以我最近注视着要与react一起工作,我正在像这样在我的App组件中验证用户身份:

应用

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的组件,该组件仅在我提供了App的auth标头后才允许发布请求,

CreateCourse

 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标头从App传递到子组件,以便不必在每个axios请求上手动放置auth标头,以供参考,这是我的repo: https:/ /github.com/SpaceXar20/full_stack_app_with_react_and_a_rest_api_p10

我总是创建单例axios实例,并在用户登录成功后为其设置标头。

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() ,请求将在标头中包含令牌。

单例axios实例是正确的方法。 以相同的方式,使用以下方法。将文件导入所需的位置,然后使用axiosapi.get。

const axiosConfig = {auth: {username: XXXX, password: YYYY}}; 
const axiosservice = axios.create(axiosConfig);
export const axiosapi = {
  /**
   * Describes the required parameters for the axiosapi.get request
   * @param {string} url  
   * @param {Object} config - The configfor the get request (https://github.com/axios/axios#request-config)   
   *
   * @returns {Promise}
   */
  get: (url, config = {}, params) => {
    return axiosservice.get(url, {
      params,
      responseType: 'json',
      transformResponse: [
        data => {
          const parsedData = typeof data === 'string' ? JSON.parse(data) : data;
          return get(parsedData);
        },
      ],
      ...config,
    })
      .then()
      .catch(error => {
        return Promise.reject(error);
      });
  },
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM