简体   繁体   中英

Enable CORS through Angular

I am using Angular 7, and i am supposed to construct a frontend, with the backend deployed on Heroku. Since i cannot edit the backend (which obviously does not have CORS enabled), i cannot access any api's and i get an error:

Access to XMLHttpRequest at ' http://ebit-front-test.herokuapp.com/register ' from origin ' http://localhost:4200 ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. register.service.ts:31

Backend returned code 0, body was: [object ProgressEvent]

Is there a way to enable CORS through Angular, or avoid this issue. I have tried with custom proxy config but it was no good.

*This question differs from the other similiar ones because they actually have access to their backend, whereas i have to solve the problem without access to backend.

You might want to setup local proxy in Angular. In angular.json add option proxyConfig pointing to your definition file:

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

and create proxy.conf.json file for example:

{
  "/register": {
    "target": "http://ebit-front-test.herokuapp.com/register",
    "secure": false
  }
}

and then from the client just call url as http.post('/register') . Tweak your proxy config so that it catches all api routes.

More reading...

CORS needs to be configured on the server for a "real" application, one that you expect non-developers to use.

However, for testing purposes you can use a proxy server to add the headers that the sever should be adding.

See for example, https://elements.heroku.com/buttons/marcus2vinicius/cors-anywhere

For everyone else having this issue i have found a way to avoid the CORS error. If you run Chrome without web security, the CORS error will disappear.

This does not enable CORS, so it is a temporary solution, if you don't have access to your backend, but need to develop frontend.

Steps to run without web security:

1) Run command prompt as administrator, and with this command kill all instances of Chrome:

taskkill /F /IM chrome.exe

2) Run new Chrome instance with web security disabled using this command:

start chrome https://teckangaroo.com/chrome-disable-web-security/ –disable-web-security –user-data-dir=”C:\teckangaroo.com”

That should do it!

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