CORS error axios

Harry Jung·2023년 11월 23일
0

Cors 에러 blocked by origin..
원인: 앱이나 postman에서는 문제가 없으나 웹에서만 문제가 됨.
이유: 웹 브라우저에서 client에서 보는 request의 https://localhost:3000 과 응답하는 backend Server의 주소:https://api.courierplease.com.au/../ 가 다르면 에러로 간주하고 웹에서는 막아버림. 즉 웹에서만 막아버림.

그렇다면 해결책:
https://localhost:3000을 https://api.courierplease.com.au로 만들어야 함.

https://velog.io/@ajm0718/Vite-axios-CORS-%ED%95%B4%EA%B2%B0%ED%95%98%EA%B8%B0

여기에 자세히 나와있음.
http:// 프로토콜
api.courierplease.com.au // 호스트
:8080 // 포트

만드는 방법은
vite.config.js


export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      "/api": {
        target: "https://jsonplaceholder.typicode.com",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
  },
});

위처럼 프로토콜과 호스트를 바꿀수가 있다.
사용하려면
api.js

export const getData = async () => {
  const response = await axios.get("/api/users");
  return response.data;
};

꼭 리스트를 해주고 실행하면 좋음.

profile
Dreamsoft

0개의 댓글

Powered by GraphCDN, the GraphQL CDN