所以我最近注视着要与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标头,这是我的回购协议: https://github.com/SpaceXar20/full_stack_app_with_react_and_a_rest_api_p10
答案 0 :(得分:1)
我总是创建一个单例的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()
时,请求的标头中将带有令牌。
答案 1 :(得分:0)
单轴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);
});
},
}