반응형
로컬호스트에 띄워놓은 react 로부터 nestjs 으로 api 호출을 하려고 한다.
fetch 함수를 사용한 POST 호출을 하는데 다음과 같은 에러를 마주할 수 있다.
Access to fetch at 'http://localhost:3000/solana-nft/getAllNftsByAddress' from origin 'http://localhost:1234' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
- 이 에러 떄문에 fetch 옵션에서
credentials: 'include'
를 제거했다.
유사한 에러 메세지는 다음과 같다.
Access to fetch at 'http://localhost:3000/solana-nft/getAllNftsByAddress' from origin 'http://localhost:1234' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
CORS 문제를 해결하기 위해서는 클라이언트가 아닌 서버에서 cors 설정을 허용해야 한다.
nestjs 서버의
main.ts
파일에 다음 처럼app.enableCors()
설정을 추가한다.async function bootstrap() { const app = await NestFactory.create(AppModule); app.enableCors(); await app.listen(3000); app.useGlobalPipes(new ValidationPipe()); } bootstrap();
api 를 호출하는 클라이언트는 별다른 설정을 안해도 된다. (no-cors 와 같은 설정)
try { fetch(url, { method: 'POST', // mode: 'no-cors', // cache: 'no-cache', // credentials: 'include', headers: {'Content-Type': 'application/json'}, // redirect: 'follow', // manual, *follow, error // referrerPolicy: 'no-referrer', body: JSON.stringify({ address: publicKey }) }).then(response => response.json()) .then(data => console.log(data));
반응형
'프로그램언어 > Javascript' 카테고리의 다른 글
React Input value as number (0) | 2022.06.14 |
---|---|
(react) JSON array 를 setState array 로 관리하여 display 하기 (0) | 2022.06.13 |
Infura ipfs (get) vs (cat) (0) | 2022.06.07 |
nestjs dotenv 설정 (0) | 2022.05.19 |
npm dependency 고정하기 (0) | 2022.05.18 |