반응형
Fetch API에서 권한 부여 헤더 설정
Node/Express 백엔드가 있으며 React Client와 함께 API를 사용하고 있습니다.사용자 등록 후 인증 헤더를 설정할 수 있도록 하고 싶습니다.이것에 의해, 이후의 요구는 인가 헤더와 함께 송신됩니다.
여기 Axios에서 어떻게 동작하는지, 여기 Fetch에서 권한 부여 헤더를 가져오는 방법을 볼 수 있습니다.
Fetch API로 이것을 어떻게 할 수 있습니까?
잘 부탁드립니다.
var url = "https://yourUrl";
var bearer = 'Bearer ' + bearer_token;
fetch(url, {
method: 'GET',
withCredentials: true,
credentials: 'include',
headers: {
'Authorization': bearer,
'X-FP-API-KEY': 'iphone', //it can be iPhone or your any other attribute
'Content-Type': 'application/json'
}
}).then(responseJson => {
var items = JSON.parse(responseJson._bodyInit);
})
.catch(error => this.setState({
isLoading: false,
message: 'Something bad happened ' + error
}));
제가 알기로는 디폴트 옵션/헤더를 사용하는 방법은 없습니다.fetch
. 이 서드파티 라이브러리를 사용하여 동작시킬 수도 있고, 모든 요청에 사용할 기본 옵션을 설정할 수도 있습니다.
// defaultOptions.js
const defaultOptions = {
headers: {
'Authorization': getTokenFromStore(),
},
};
export default defaultOptions;
그런 다음 다음과 같은 기본 옵션을 사용합니다.
import defaultOptions from './defaultOptions';
// With default options:
fetch('/auth', defaultOptions);
// With additional (non-default) options:
fetch('/auth', { ...defaultOptions, body: JSON.stringify(additionalData) });
헤더를 fetch의 두 번째 파라미터로 전달할 수 있습니다.
fetch(<your url>, {
headers: {
authorization: <whatever is needed here>
}
})
headers: {
'Authorization': `Bearer ${localStorage.getItem("token")}`,
'Accept': 'application/json',
'Content-Type': 'multipart/form-data;
},
제 경우, 문제는 제가 세팅한 스트링이Authorization
아직 생성되지 않았습니다.약속으로 포장해야 했는데, 갑자기 효과가 있었어요.
let authHeader: string = await SearchAuthService.getAuthHeader();
언급URL : https://stackoverflow.com/questions/45535913/setting-authorization-header-in-fetch-api
반응형
'programing' 카테고리의 다른 글
현재 JSON 개체(예: {"name":"value"})를 '시스템' 유형으로 역직렬화할 수 없습니다.컬렉션포괄적인.리스트 1 (0) | 2023.03.22 |
---|---|
WebStorm 2018.1.4 + ESLint: TypeError: 이것.CliEngine은 생성자가 아닙니다. (0) | 2023.03.22 |
Wordpress/Apache - 이미지 파일 이름에 유니코드 문자가 포함된 404 오류 (0) | 2023.03.22 |
동형/유니버설 반응의 Image onLoad 이벤트 - 이미지 로드 후 이벤트 등록 (0) | 2023.03.12 |
AngularJS - 여러 리소스 쿼리가 완료될 때까지 기다립니다. (0) | 2023.03.12 |