CORS Policy and Handling CORS in Nodejs and Spring Boot


CORS stands for Cross-Origin Resource Sharing. It is a security feature to prevent cross-origin requests to different domains. It prevents webpages from making a request to a other domain than the one that served the web page. When building an application that needs to communicate to different APIs on different domains it gives cors error. There is an SOP i.e. same origin policy which is the foundation of Cors policy according to SOP a web page can only make requests to the same origin. What is Origin Here?
An origin is defined by the combination of three components:
Scheme (or Protocol): This can be
http
,https
,ftp
, etc.Host: This is the domain (e.g.,
Badal.com
) or IP address.Port: This is the port number, typically omitted for HTTP (80) and HTTPS (443).
What is CORS?
Cors is a mechanism to prevent unauthorized requests to a domain. CORS is crucial because it ensures that your data and resources are safe. If there is no CORS policy then it will be easier to make malicious requests to any domain from another domain. By enforcing CORS policies, you can control who gets access to your valuable information and resources, making the web a safer place for everyone.CORS is crucial for web security because it prevents unauthorized access to sensitive data and resources. Without CORS, malicious websites could potentially make requests to trusted domains on behalf of the user. To maintain a Secure environment, it's essential to enforce CORS policies to ensure that only trusted domains can access your resources.
CORS Errors
when the server detects a cors policy violation, it generates a CORS error. CORS errors typically come in the form of JavaScript errors that you can see in the browser's developer console. The most common CORS error is:
This error message indicates that a request from http://
localhost:4200
to http://localhost:3000/
balance-sheet
has been blocked due to CORS policy violations.
CORS handling in NodeJs
To handle CORS in nodejs you have to follow the following steps:
1. Install cors
middleware
npm install cors
2. Import the cors module in the express app and use it
const express = require('express');
const cors = require('cors');
const app = express();
// Enable CORS for all routes
app.use(cors({origin:true}));
//other routes and middleware functions
app.listen(3000, () => {
console.log(`Server is running on port 3000`);
});
app.use(cors({origin:true}))
it is used to allow all origin to access the server resource.
Sometimes you do not want to allow all the origins to access the server resource in this case you can pass a corsOptions to this middleware function. These corsOptions can be static as mentioned below or dynamic. In dynamic options server will determine the allowed origin based on the incoming request
const express = require('express');
const cors = require('cors');
const app = express();
// Enable CORS for all routes
const options = {
origin: ['https://test-domain1.com', 'https://test-domain2.com'], // Allow requests from origin mentioned here
methods: 'GET,PATCH,POST,DELETE', // allow only specific http methods
optionsSuccessStatus: 204, // Set the HTTP status code for OPTIONS requests
};
app.use(cors(corsOptions));
//other routes and middleware functions
app.listen(3000, () => {
console.log(`Server is running on port 3000`);
});
CORS handling in Spring Boot
In spring boot you can handle CORS using various method
1.Using @CrossOrigin
annotation
@CrossOrigin
is a spring annotation used to handle cors in spring boot.
@RestController
public class BookController {
@GetMapping("/book")
@CrossOrigin(origins = {"https://test-domain1.com", "https://test-domain2.com"})
public ResponseEntity<List<Book>> getBooks() {
// Your controller logic here
}
}
2.Using Java Configurations
@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("https://text-domain1.com", "https://test-domain2.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
}
}
3.Using application.properties file
You can directly handle cors in application.properties file or application.yaml file
# CORS configuration
spring.mvc.cors.allowed-origins=https://test-domain1.com, https://test-domain2.com
spring.mvc.cors.allowed-methods=GET,PUT,DELETE
spring.mvc.cors.allowed-headers=*
I hope this article has provided you with valuable insights into CORS and its implementation in both Node.js and Spring Boot. Stay tuned for more informative articles, and see you in the next one. Follow me for more engaging software engineering content!
Happy Coding🚀🚀
Subscribe to my newsletter
Read articles from Badal Jha directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Badal Jha
Badal Jha
Enthusiastic software developer with a knack for crafting clean and functional code. Driven by a curiosity to build innovative solutions, I'm dedicated to making a meaningful impact through software development.