Итак, я недавно начал работать с реагировать, я аутентифицирую пользователя в своем компоненте приложения следующим образом:
Приложение
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, который позволяет отправлять запрос только в том случае, если я предоставил заголовок авторизации из приложения,
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(`/`)
})
};
Мне было интересно, смогу ли я передатьзаголовок аутентификации из приложения App для дочерних компонентов без использования props или контекстного API, так что мне не нужно вручную ставить заголовки auth на каждый запрос axios, для справки это мое репо: https://github.com/SpaceXar20/full_stack_app_with_react_and_a_rest_api_p10