Home > front end >  Angular - Every request is being blocked by CORS
Angular - Every request is being blocked by CORS

Time:11-16

I'm making an angular 12 application with a java back-end for my university. I was testing angular's http client but I can't make any request because it's being blocked by CORS. First, I tried making a POST request to my back-end server, but no luck. Angular Code:

const API_URL = 'http://localhost:9080'

@Injectable({
  providedIn: 'root'
})

export class AuthService {

  constructor(private http:HttpClient, private router:Router) { }

  login(user:User) { 
    this.http.post(`${API_URL}/login`, user, {observe:'response'}).subscribe(result => { 
      console.log(result)
    })
  }

The response was this.

So, I searched and found that this is most server-side, and even though I can make requests normally in Insomnia/Postman, I tried configuring cors on my server.xml.

But then I had the idea to try and consume external APIs. I tried making a GET Request to Google, only to get this back:

Response from google

And this is occurring with every external API, So I don't think the problem is server-side, but rather with Angular, but I couldn't find any solution that wouldn't say the problem is server-side, but it can't be since I can't make any request to any website, right?

CodePudding user response:

Although it seems like your Backend and Frontend are on the same origin, it is in fact not the case

These are not same origin because they use different ports:
http://example.com:80
http://example.com:8080

Two URLs have the same origin if the protocol, port (if specified), and host are the same for both.

Fixing CORS is always done server-side. Basically the Browser doesn't allow you to make requests from scripts of a different location than your where your frontend is hosted for security reasons. Read in detail here

For develop you may disable the Browser CORS check. You can download Browser extension to do so or use chrome flags. Read here about the flags

"--user-data-dir=/tmp/chrome-sesh", "--disable-web-security"
  • Related