Deadly CORS when http://localhost is the origin

后端 未结 9 1310
迷失自我
迷失自我 2020-11-22 00:54

I am stuck with this CORS problem, even though I set the server (nginx/node.js) with the appropriate headers.

I can see in Chrome Network pane -> Response Headers:

9条回答
  •  鱼传尺愫
    2020-11-22 01:37

    I decided not to touch headers and make a redirect on the server side instead and it woks like a charm.

    The example below is for the current version of Angular (currently 9) and probably any other framework using webpacks DevServer. But I think the same principle will work on other backends.

    So I use the following configuration in the file proxy.conf.json:

    {
      "/api": {
        "target": "http://localhost:3000",
        "pathRewrite": {"^/api" : ""},
       "secure": false
     }
    }
    

    In case of Angular I serve with that configuration:

    $ ng serve -o --proxy-config=proxy.conf.json
    

    I prefer to use the proxy in the serve command, but you may also put this configuration to angular.json like this:

    "architect": {
      "serve": {
        "builder": "@angular-devkit/build-angular:dev-server",
        "options": {
          "browserTarget": "your-application-name:build",
          "proxyConfig": "src/proxy.conf.json"
        },
    

    See also:

    https://www.techiediaries.com/fix-cors-with-angular-cli-proxy-configuration/

    https://webpack.js.org/configuration/dev-server/#devserverproxy

提交回复
热议问题