添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Access to XMLHttpRequest at 'http://localhost:5000/api/hello' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
xhr.js:177 GET http://localhost:5000/api/hello net::ERR_FAILED createError.js:16
Uncaught (in promise) Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:84)

보안정책 때문에 cors 정책이 있는데 cors정책 때문에 막힌 에러임

이것을 proxy로 해결

C:\practices\react-node\boiler-plate> cd client
C:\practices\react-node\boiler-plate\client> npm i http-proxy-middleware

client의 src에 setUpProxy.js를 생성

[setUpProxy.js]

const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
    app.use(
        '/api',
        createProxyMiddleware({
            target: 'http://localhost:5000',
            changeOrigin: true,

[LandingPage.js]

import React, { useEffect } from 'react';
import axios from 'axios';
export default function LandingPage() {
    useEffect(() => {
        axios.get('/api/hello')
            .then(response => console.log(response.data));
    }, [])
    return(
            LandingPage

LandingPage의 axios.get url은 원래대로 바꿔줌

실행하면 다음과 같은 결과가 뜬다.

frontend 3000번포트에 backend 5000번 포트에서 보낸 안녕하세요가 출력됨