react.js
fetch 사용시 credentilas
FaustK
2020. 4. 8. 23:54
credentials 설정을 해주지 않으면, fetch 가 제대로 안 되는 경우가 많다.
Access-Control-Allow-Credentials
Access-Control-Allow-Credentials
응답헤더 Access-Control-Allow-Credentials 는 요청의 자격증명 모드(Request.credentials)가 "include" 일때, 브라우저들이 응답을 프로트엔드 자바스트립트 코드에 노출할지에 대해 알려줍니다.
developer.mozilla.org
다음과 같이 credentials 를 해주어야 한다
예1
postLogin(body) {
fetch('http://localhost:5001/users/login', {
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
credentials: 'include'
})
.then(res => res.json())
.then(json => {
if (json.loginCheck === 'success') {
this.props.onChangeLoginTrue();
this.props.history.push('/main');
}
if (json.loginCheck === 'failed') {
console.log('login failed');
}
});
}
예2
fetchUserData() {
fetch('http://localhost:5001/users/info', {
credentials: 'include'
})
.then(res => res.json())
.then(json => {
if (json.id) {
this.setState({ email: json.email, name: json.name });
}
});
}