IT이야기

fetch()는 헤더를 보내는가

cyworld 2021. 4. 23. 22:01
반응형

fetch ()는 헤더를 보내지 않습니까?


브라우저에서 다음과 같은 POST 요청을 보내고 있습니다.

fetch(serverEndpoint, {
    method: 'POST',
    mode: 'no-cors', // this is to prevent browser from sending 'OPTIONS' method request first
    redirect: 'follow',
    headers: new Headers({
            'Content-Type': 'text/plain',
            'X-My-Custom-Header': 'value-v',
            'Authorization': 'Bearer ' + token,
    }),
    body: companyName
})

요청이 내 백엔드에 도달 할 때까지 헤더 X-My-Custom-Header포함되지 않습니다 Authorization.

내 백엔드는 다음과 같은 Firebase 용 Google Cloud 함수 (기본적으로 Node.js 엔드 포인트)입니다.

exports.createCompany = functions.https.onRequest((req, res) => {
    let headers = ['Headers: ']
    for (let header in req.headers) {
        headers.push(`${header} : ${req.headers[header]}`)
    }
    console.log(headers)
    ...
}

구글 클라우드 중포 기지에 대한 기능의 콘솔 로그는 포함되어 있지 X-My-Custom-Header않으며 Authorization헤더를.

뭐가 잘못 되었 니?


편집 1

따라서 Chrome에서 개발 도구를 사용 하여 브라우저에서 헤더도 전송 되지 X-My-Custom-Header않는지 확인했습니다 Authorization. 이제 질문은 다음과 같습니다. 왜? 어떻게 고치나요?


편집 2

내 앱에 대한 추가 정보 : React 앱입니다. 서비스 워커를 비활성화했습니다. Request사용하여 헤더 를 만들고 구체적으로 추가 하려고했습니다 req.headers.append(). 헤더는 여전히 전송되지 않습니다.


동일 출처 정책은 웹 페이지가 다른 출처에서 리소스에 보낼 수있는 요청의 종류를 제한합니다.

에서 no-cors 모드를 가진 사람들 - 브라우저는 "간단한"요청 보내기로 제한됩니다 safelisted 방법safelisted 헤더 만.

같은 헤더 크로스 원산지 요청을 보내려면 Authorization하고 X-My-Custom-Header, 드롭해야 no-cors모드 지원 프리 플라이트 요청을 ( OPTIONS).

"단순"요청과 "비 단순"요청의 차이점은 역사적 이유 때문입니다. 웹 페이지는 항상 다양한 수단 (양식 생성 및 제출 등)을 통해 출처 간 요청을 수행 할 수 있으므로 웹 브라우저가 출처 요청을 보내는 원칙적인 수단 ( 출처 간 리소스 공유 또는 CORS)을 도입했을 때 이러한 "간단한"요청은 비행 전 OPTIONS확인 에서 제외 될 수 있다고 결정했습니다 .


첫째 : 대신 객체를 사용하십시오 new Headers(..).

fetch('www.example.net', {
  method: 'POST',
  headers: {
    'Content-Type': 'text/plain',
    'X-My-Custom-Header': 'value-v',
    'Authorization': 'Bearer ' + token,
  }
});

두 번째 : 알아두면 좋은 점, 헤더는 소문자로 fetch!!

셋째 : no-cors모드는이 화이트리스트에 대한 헤더 사용을 제한합니다.

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type그리고, 그 값은 ( application/x-www-form-urlencoded, multipart/form-data, text/plain)

그래서 Content-Type헤더 전송되고 X-My-Custom-Header또는 Authorization.


이것을 시도해 볼 수 있습니까?

fetch(serverEndpoint, {  
  credentials: 'include'  
})

Ref. https://developers.google.com/web/updates/2015/03/introduction-to-fetch#sending_credentials_with_a_fetch_request


첫째 : exports.createCompany 함수에서 헤더를 호출 할 때 소문자 대신 let headers = ['Headers: ']대문자를 H사용하여 h오류를 일으킬 수 있습니다. 또한 헤더에 있으면 안되는 토큰 뒤에 쉼표가 있습니다.

2nd : 반응 네이티브에서 가져 오기 요청을 사용할 때마다 header:필요하지 않습니다 new Headers.

이 시도: fetch(serverEndpoint, { method: 'POST', mode: 'no-cors', redirect: 'follow', headers:{ 'Content-Type': 'text/plain', 'X-My-Custom-Header': 'value-v', 'Authorization': 'Bearer ' + token }, body: companyName })


나는 또한 이와 같은 문제가 있었다. 나는 자바 스크립트에서 'no-cors'를 제거하고 서버 측 스프링 부트에 다음을 추가하여 해결했습니다.

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        protected void configure(HttpSecurity httpSecurity) throws Exception {
             .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()

        }
    }

ReferenceURL : https://stackoverflow.com/questions/45591594/fetch-does-not-send-headers

반응형