DEV Community

Cover image for Fixing 401 Error with CORS Preflights (with Spring boot)
Udith Indrakantha
Udith Indrakantha

Posted on • Originally published at webtechmora.blogspot.com

2

Fixing 401 Error with CORS Preflights (with Spring boot)

When the web application runs on a different domain and the server runs on another domain, we have to deal with cross origin requests. But, if we don’t know the mechanism of cross origin resource sharing (CORS), we will end up with errors like 401.

Error in brief

My Angular web application runs on port 4200, and my spring boot application runs on server on port 8080. I could not enable CORS in my backend, so, I got an error when sending a request from my application like this.

Alt Text

Reason

My pre-flight request is not responded with status OK(200).

Solution

I enabled CORS in my backend. To do this, there are several methods. Here in my post, I have shown the easiest way to do that. But, if you are interest in knowing other ways, click me )

By using Web Security in Spring Boot,

You have to create a web security configuration class. I hope everybody creates that class for backend authentication purposes.

If you have already created that class, inside configure( HttpSecurity httpSecurity ) method ,add this line httpSecurity.cors();

Alt Text

It’s that simple !!!
Originally published at https://webtechmora.blogspot.com by Udith.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay