简体   繁体   中英

Webpack devserver proxy not working to get round CORS issue

I have a React app which is running webpackdevserver on port 3000.

I have an AWS.NetCore Lambda server running localhost on port 5050.

When I try and make a request I am getting the cors error:

Access to fetch at 'http://localhost:5050/' from origin 'http://localhost:3000' 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.

I was hoping to use a proxy, as per the documtation here in order to forward my requests on using the same domain to get round this.

https://medium.com/@drgenejones/proxying-an-external-api-with-webpack-serve-code-and-a-restful-data-from-separate-endpoints-4da9b8daf430

However it is not working, I don't see any difference at all with the settings applied, can anyone help?

devServer: {
  port: 3000,
  disableHostCheck: true,
  compress: true,
  host: 'localhost',
  proxy: {
    '/': {
      target: 'http://localhost:5050',
      secure: false,
    },
  },
},

My JavaScript to call the server is like this... I have also tried with the url http://localhost:3000 but this just returns a bad request error.

  const result = await fetch('http://localhost:5050', {
    method: 'POST',
    headers: new Headers({ 'Access-Control-Allow-Origin': '*' }),
    body: JSON.stringify({
      method: 'upload',
      test: 'test',
    }),
  });

I guess the issue is to set / which could just fetch the current server so you might need to differentiate between your web app vs your server (most likely via a specific path such as /api , but you can choose to pass this path to your proxy server or not).

So you would change as following:

  • Your configuration of proxy first to take api to go through proxy:
proxy: {
  '/api': {
    target: 'http://localhost:5050',
    pathRewrite: {'^/api' : ''}, // In this case we don't pass `api` path
  }
}
  • Next thing is to change your code to call the same domain + port 3000 normally (proxy would do the rest for you by passing to your server with port 5050 which you configured):
const result = await fetch('http://localhost:3000/api', {
  // ...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM