Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

spring boot - Cross Origin Resource Sharing (CORS) in Angular or Angular 6. Problem while you make cross domain calls on localhost with different ports

I have come across a situation where I make a call from my angular 6 application to my spring boot application. When I call an HTTP post method in angular to the application running on a different port it throws an exception.

Access to XMLHttpRequest at 'http://localhost:8080/api' 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.

My Angular application Running on 'http://localhost:4200' port number:4200 My Spring Boot application running on 'http://localhost:8080/api': port number:8080.

There is no direct answer to solve this problem. There are few hacks to disable the security in chrome and using NGINX you can resolve this issue.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To Solve the above problem

  1. First you need to share the Spring boot resource for the port 4200. Annotate the class or method with @CrossOrigin(origins = "http://localhost:4200") of resource you want to share.

  2. Yo have to configure proxy in angular application. So create a proxy.json file in angular root application. and the content goes below

    {
    "/api/*": {
        "target": "http://localhost:8080",
        "secure": "false",
        "logLevel": "debug",
        "changeOrigin": true
    }
    

    }

  3. And then run ng serve --proxy-config proxy.json this command it will compile the code. You should see something like this on a console.

    building modules 3/3 modules 0 active[HPM] Proxy created: /api -> 
    http://localhost:8080 Subscribed to http-proxy events: [ 'error', 'close' ]
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...