Express doesn't set a cookie

后端 未结 10 1601
花落未央
花落未央 2020-12-14 01:45

I have problem with setting a cookies via express. I\'m using Este.js dev stack and I try to set a cookie in API auth /login route. Here is the cod

10条回答
  •  生来不讨喜
    2020-12-14 02:07

    A cookie can't be set if the client and server are on different domains. Different sub-domains is doable but not different domains and not different ports.

    If using Angular as your frontend you can simply send all requests to the same domain as your Angular app (so the app is sending all API requests to itself) and stick an /api/ in every HTTP API request URL - usually configured in your environment.ts file:

    export const environment = {
      production: false,
      httpPhp: 'http://localhost:4200/api'
    }
    

    Then all HTTP requests will use environment.httpPhp + '/rest/of/path'

    Then you can proxy those requests by creating proxy.conf.json as follows:

    {
      "/api/*": {
        "target": "http://localhost:5200",
        "secure": false,
        "changeOrigin": true,
        "pathRewrite": {
          "^/api": ""
        }
      }
    }
    

    Then add this to ng serve:

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

    Then restart your app and it should all work, assuming that your server is actually using Set-Cookie in the HTTP response headers. (Note, on a diff domain you won't even see the Set-Cookie response header, even if the server is configured correctly).

提交回复
热议问题