others-how to resolve 'cors error' when sending request to restful web service implemented by springboot ?

1. Purpose

In this post, I will show you how to resolve ‘cors error’ when sending request to restful web service implemented by springboot.

2. Solution

2.1 The error details

When we visit “http://domain-A”, which contains a ajax request to “http://domain-B” ,we got cors error.

The server code for http://domain-B:

    @GetMapping
    fun index(): List<Message> {
        logger.info("got list request")
        var result = listOf(
            Message("1","hello1"),
            Message("2","Object"),
            Message("3","Privot"),
        )
        msgService.msgService();
        return result
    }

The client code, you can see that the client is using axios to send a http Get request to http://domain-B:

    doMsg() {
      console.log("start do msg:");

      axios.get("http://domain-B").then(
        (response) => {
          console.log("got response:", response);
          if (response.data) {
            response.data.forEach((element) => console.log(element));
          }
        },
        (response) => {
          console.error(response);
        }
      );
    },

Why does the cors error happen?

2.2 What is cors error?

For security reasons, browsers prohibit AJAX calls to resources residing outside the current origin. For example, as you’re checking your bank account in one tab, you could have the evil.com website open in another tab. The scripts from evil.com should not be able to make AJAX requests to your bank API (e.g., withdrawing money from your account!) using your credentials.

CORS is a mechanism that can be found in modern web browsers like Chrome, Firefox, Safari, and Edge. It prevents Domain A from accessing resources on Domain B without explicit permission.

Cross-Origin Resource Sharing (CORS) is a standard that allows a server to relax the same-origin policy. This is used to explicitly allow some cross-origin requests while rejecting others. For example, if a site offers an embeddable service, it may be necessary to relax certain restrictions. Setting up such a CORS configuration isn’t necessarily easy and may present some challenges. In these pages, we’ll look into some common CORS error messages and how to resolve them.

The CORS behavior, commonly termed as CORS error, is a mechanism to restrict users from accessing shared resources. This is not an error but a security measure to secure users or the website which you are accessing from a potential security breach.

2.3 How to fix it?

We can fix cors error by telling the server to allow requests from any source, Just as follows:

You can add an @CrossOrigin annotation to your @RequestMapping annotated handler method in order to enable CORS on it. By default @CrossOrigin allows all origins and the HTTP methods specified in the @RequestMapping annotation:

    @RequestMapping
    @CrossOrigin
    fun index(): List<Message> {
        logger.info("got list request")
        var result = listOf(
            Message("1","hello1"),
            Message("2","Object"),
            Message("3","Privot"),
        )
        msgService.msgService();
        return result
    }

Or you can enable CORS for the whole controller:

@CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {

    @RequestMapping("/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }

    @RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}

Or if you want to enable CORS only on some patterns of URL, you can do as follows:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
            .allowedOrigins("http://domain2.com")
            .allowedMethods("PUT", "DELETE")
            .allowedHeaders("header1", "header2", "header3")
            .exposedHeaders("header1", "header2")
            .allowCredentials(false).maxAge(3600);
    }
}

2.4 How to enalbe CORS globally?

You can use @Configuration to enable CORS for the whole app:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

Now it works.



3. Summary

In this post, I demonstrated how to enable CORS using java or spring framework. That’s it, thanks for your reading.