[TROUBLESHOOTING] Another CORS ERROR

THOVY·2023년 8월 22일
0

TROUBLESHOOTING

목록 보기
41/41

Error ❌

Error❌
Access to fetch at 'https://localhost:8000/test' from origin 'http://localhost:3000' has been blocked by CORS policy: 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.

client에서 server로 요청을 보내니 에러가 발생한다.

하지만 서버에도 요청이 들어가고, 클라이언트에서 보내는 다른 요청이 모두 제대로 작동하는 걸로 봐서, proxy 같은 문제가 아니라 해당 메서드와 요청에만 문제가 있는 건데, 무슨 문제인지 모르겠다.

// client.jsx

function testRequest(){
  fetch(BASE_URL + "/test",{
    method:"get",
    headers:{
      "Content-Type": "application/json",
    }
  })
    .then(res => {
    console.log('first response', res);
    res.json()
  })
    .then(res =>{
    console.log('second response', res);
  })
}

...

<button type='button' onClick={testRequest}>Test Request</button>
# server.py

@app.get('/test')
async def test(request:Request):
	print(request)
	return 'test_response'

Solution ✅

server의 메서드가 비동기면, client의 메서드도 비동기여야한다.

// client.jsx

// ❌ wrong
function testRequest(){
  fetch(BASE_URL + "/test", {
    ...

// ✅ correct
async function testRequest(){
  await fetch(BASE_URL + "/test", {
    ...

제발 멍청해지지 말자! 제발!

profile
BEAT A SHOTGUN

0개의 댓글