Angular interceptors and CORS

前端 未结 2 1939
清歌不尽
清歌不尽 2021-01-18 11:31

I am trying to write an interceptor to add a token to all HTTP requests using Angular. I am using roughly the recipe given here - https://thinkster.io/interceptors

S

2条回答
  •  花落未央
    2021-01-18 12:02

    The same-origin policy is a critical security mechanism that restricts how a document or script loaded from one origin can interact with a resource from another origin. It helps isolate potentially malicious documents, reducing possible attack vectors.

    This makes your app more secure.

    CORS gives web servers the ability to say they want to opt into allowing cross-origin access to their resources.

    Instead of using CORS, I recommend you use a proxy in your angular server, so:

    • in the browser, the real resource wont be displayed (more privacy and security)
    • your code is more isolated from the specific source

    Implementation

    Create a proxy.conf.json in your app

    {
    
        "/client-api/*": {
          "target": "http://127.0.0.1",
          "pathRewrite": { "^/client-api": "" },
          "secure": false,
          "logLevel": "debug",
          "changeOrigin": true
        }
      }
    

    In your angular.json file, under projects..architect.serve.options add

    "proxyConfig": "src/proxy.conf.json"
    

    Where you make the http request, just use the url origin client-api.

    For example, to get the list of countries, you request client-api/countries, and the proxy will transform it to http://127.0.0.1/countries

提交回复
热议问题