简体   繁体   中英

CORS errors when deploying Spring Boot and Angular app in Docker

I have deployed 3 docker containers - for the database, the backend (Spring boot) and the frontend (Angular). However, when I am visiting the website (Google Cloud VM), I am getting CORS error for all the requests to backends. The backend is run on 8080.

I am getting CORS when I am visiting the IP:80

Why is this happening? What is the workaround?

Here is the way I have used CrossOrigin in the controller.

@CrossOrigin("*")
@RestController
@RequestMapping("/api")
public class CustomerController {

Any help is appreciated.

@Cross: will be applied for Single Page it wont be applicable for entire application So I would suggest you to follow the approach as defined in below Similar scenario link: CORS Config . where you can defined the filter for entire application with more control over the configuration for CORS.

And also if you have Spring security integrated with your app you need to handle some more config changes in order to make it work.

Hope this was helpful

You are not allowed to call URLs from your scripts that are not found under the same domain that you page was rendered:

For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was loaded from, unless the response from other origins includes the right CORS headers.

Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

You actually have 3 Options:

  1. Add the 8080 port (port of your Spring Boots Tomcat server) to your exceptions (see: https://spring.io/guides/gs/rest-service-cors/ )
  2. Use a reverse proxy like nginx that routes your requests to the API or serves the Angular resources depending on the request
  3. Serve the Angualr resources from your Spring Boot app

You could use a proxy server at your UI side in express.js, Here is an example code:

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

just redirect the request to you Spring boot service inside the api calls.

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