programing

webpack dev 서버 CORS 문제

skycolor 2023. 3. 18. 08:25
반응형

webpack dev 서버 CORS 문제

사용하고 있다webpack-dev-server v1.10.1Redux 프로젝트를 활성화하기 위해 다음과 같은 옵션을 선택할 수 있습니다.

contentBase: `http://${config.HOST}:${config.PORT}`,
quiet: false,
noInfo: true,
hot: true,
inline: true,
lazy: false,
publicPath: configWebpack.output.publicPath,
headers: {"Access-Control-Allow-Origin": "*"},
stats: {colors: true}

JS 에서는,request부터superagentHTTP GET 콜을 생성하다

request
          .get(config.APIHost + apiUrl)
          .set('Accept', 'application/json')
          .withCredentials()
          .end(function (err, res) {
                if (!err && res.body) {
                    disptach(() => {
                        return {
                            type: actionType || GET_DATA,
                            payload: {
                                response: res.body
                            }
                        }
                    });
                }
          });

하지만 CORS 오류가 발생했습니다.

XMLHttpRequest cannot load http://localhost:8000/api/getContentByType?category=all. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5050' is therefore not allowed access

이 문제를 해결할 방법이 있나요?정말 감사해요.

다른 방법으로 필요한 CORS 헤더를 개발 서버에 직접 추가하는 방법도 있습니다.

devServer: {
  ...
  headers: {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
    "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
  }
}

문서 링크

webpack-dev-server 1.15를 사용합니다.X 컨피규레이션파일로 다음의 설정을 사용할 수 있습니다.

devServer: {
   contentBase: DIST_FOLDER,
   port: 8888,
   // Send API requests on localhost to API server get around CORS.
   proxy: {
      '/api': {
         target: {
            host: "0.0.0.0",
            protocol: 'http:',
            port: 8080
         },
         pathRewrite: {
            '^/api': ''
         }
      }
   }
},

이 예에서는, 다음의 모든 콜을 리다이렉트 합니다.http://0.0.0.0:8888/api/*로.http://0.0.0.0:8080/*CORS가 해결되었습니다.

같은 문제가 발생했지만 API가 https://api...(https://api...)로 되어 있었습니다.서버를 https로 기동해, https://localhost:8080 을 사용할 필요가 있었습니다.

devServer: {
    https: true,
    headers: {
        "Access-Control-Allow-Origin": "*",
    },
    // ....
}

에서 JavaScript를 실행하고 있습니다.localhost:5050API 서버는localhost:8000이것은 같은 오리진 정책에 위반되기 때문에 브라우저는 이를 허용하지 않습니다.

API 서버를 변경하여 CORS를 이노블로 하거나 Webpack-dev-server 페이지의 "Combining with existing server"의 지시에 따라 자산 서비스를 webpack-dev-server 및 자체 API 서버와 결합할 수 있습니다.

여기에는 2가지 해결책이 있습니다.첫 번째는 클라이언트 측에서 프록시를 셋업하고 두 번째는 서버에서 CORS를 셋업하는 것입니다.CORS는 서버의 문제입니다.서버는 다른 소스로부터의 액세스를 허가하지 않습니다.다른 포트를 사용하는 경우에도 소스가 다른 것으로 간주됩니다.

첫 번째 솔루션

백엔드 코드에서 다음 헤더를 설정해야 합니다.다음은 express node.js의 예입니다.

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Methods",
    "OPTIONS, GET, POST, PUT, PATCH, DELETE"
  );
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
  next();
});

두 번째 솔루션:

webpack config.display에서 변수를 전달하려면

module.exports=function(env){
return {}} 

대신

module.exports={}

우리는 이것을 주입한다.env대본을 통해서요.

"dev-server": "webpack-dev-server --env.api='https://jsonplaceholder.typicode.com/users'",

이것으로 webpack은 webpack.config.webpack 내의 이 환경에 액세스 할 수 있게 되었습니다.

module.exports = function ({
  api = "https://jsonplaceholder.typicode.com/users",
}) {
  return {
    entry: { main: "./src/index.js" },
    output: {
      path: path.resolve(__dirname, "public"),
      filename: "[name]-bundle.js",
      publicPath: "/",
    },
    mode: "development",
    module: {
      rules: [
        {
          loader: "babel-loader",
          test: /\.js$/,
          exclude: [/node_modules/],
        },
        
        {
          // Load other files, images etc
          test: /\.(png|j?g|gif|ico)?$/,
          use: "url-loader",
        },
        {
          test: /\.s?css$/,
          use: ["style-loader", "css-loader", "sass-loader"],
        },
      ],
    },
    //Some JavaScript bundlers may wrap the application code with eval statements in development.
    //If you use Webpack, using the cheap-module-source-map setting in development to avoid this problem
    devtool: "cheap-module-eval-source-map",
    devServer: {
      contentBase: path.join(__dirname, "public"),
      historyApiFallback: true,
      proxy: {
        "/api": {
          changeOrigin: true,
          cookieDomainRewrite: "localhost",
          target: api,
          onProxyReq: (proxyReq) => {
            if (proxyReq.getHeader("origin")) {
              proxyReq.setHeader("origin", api);
            }
          },
        },
      },
    },
    
  };
};

언급URL : https://stackoverflow.com/questions/31602697/webpack-dev-server-cors-issue

반응형