所以我最近开始使用 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/