본문 바로가기

카테고리 없음

mini-node-server[ 오류 해결 : index.html:1 Access to fetch at 'http://localhost:4999/upper' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allo..

 

오류내용

index.html:1 Access to fetch at 'http://localhost:4999/upper' from origin 'http://127.0.0.1:5500' 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에러 인줄 알았는데 

알고보니 밑에서 head없이 end 메소드만 사용해서 나타나는 오류였음

const http = require("http");

const PORT = 4999;

const ip = "localhost";

const server = http.createServer();
server.on("request", (request, response) => {
  const { method, url } = request;

  console.log(
    `http request method is ${method}, url is ${url}`
  );


  let body = [];
  request
    .on("data", (chunk) => {
      body.push(chunk);
    })
    .on("end", () => {
      body = Buffer.concat(body).toString();
      // 여기서 `body`에 전체 요청 바디가 문자열로 담겨있습니다.

      if(method === "OPTIONS") {
        response.writeHead(200, defaultCorsHeader);
        response.end("hello mini-server sprints")
      }
      if(method === "POST" && url === "/upper") {
        response.writeHead(200, defaultCorsHeader);
        response.end(body.toUpperCase());
      } else if(method === "POST" && url === "/lower") {
        response.writeHead(200, defaultCorsHeader);
        response.end(body.toLowerCase());
      } else {
        //에러로 처리한다. bad request
        response.on("error", (err) => {
          console.error(err);
        });
      }
    });
    

  // response.writeHead(200, defaultCorsHeader); 
  // response.end("hello mini-server sprints"); // 여기부분이 오류 이유였음 head없이 end 메소드사용
  // 해드메소드를 넣으니 head가 중복된다고 해서 중복되는곳에다가 값을 넣음(OPTIONS 라인 27)
});

server.listen(PORT, ip, () => {
  console.log(`http server listen on ${ip}:${PORT}`);
});

const defaultCorsHeader = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type, Accept",
  "Access-Control-Max-Age": 10,
};