dearn44
dearn44

Reputation: 3432

Invalid CORS request for PUT with AngularJS

I have a mapping in my Spring application that looks like this:

@PutMapping(path="/test/{id}")
public @ResponseBody Shop putTest(@PathVariable("id") long id,
                                  @RequestBody User user {
....

When trying to call this endpoint with Angular by doing:

$http({
   method: 'PUT',
   url: 'https://localhost:8000/api/test',
   data: senddata,
   params:{'id':id},
   headers: {
     "Content-Type": "application/json; charset=utf-8"
   }
})

enter image description here

Is there something wrong with my request, if so how can I fix it?

Upvotes: 2

Views: 2731

Answers (3)

Caius Cosades
Caius Cosades

Reputation: 81

Presumably, your Spring app is served on a different port to your angular app? To the browser, this counts as a different origin and so requests will fail unless the server's responses contain an Access-Control-Allow-Origin header. You will need to configure your spring app accordingly.

This is the browser's Same Origin Policy, which protects users again cross-site request forgery. E.g. Imagine an evil mastermind creates a seemingly innocent website called evil.com, which fires off a load of AJAX requests to various banking servers hoping you're logged into one of them (i.e. you have a non-expired cookie). Unless the banks' servers have their access control header set to allow requests from anywhere (they shouldn't), the requests should fail. A GET request will actually succeed because the browser doesn't know it shouldn't have sent it until it gets the headers from the response, but the browser will stop the JS code reading the response, so it's OK. For 'unsafe' requests like POST and PUT, etc. the browser does a pre-flight request first (using the OPTIONS method) to get the headers. If the domain the page is loaded from isn't included in the list of allowed origins, the unsafe request isn't made.

Upvotes: 1

hrvoj3e
hrvoj3e

Reputation: 2754

This is normal behavior when Origin is not well defined.

Look at the server side setup. Browsers are sending OPTIONS request before your PUT request.

Read more about Access-Control-Request-* headers.

Upvotes: 0

Edison Junior
Edison Junior

Reputation: 320

your backend have to know of where requests come. just for you test that request, you can expecific where the request cane from, just add that anotation.

@CrossOrigin(origins = "http://localhost:9000")
@PutMapping(path="/test/{id}")
public @ResponseBody Shop putTest(@PathVariable("id") long id,
                                  @RequestBody User user {
....

i hope it useful

Upvotes: 2

Related Questions