2

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?

malbarmavi
  • 18,795
  • 4
  • 45
  • 73
dearn44
  • 2,628
  • 1
  • 24
  • 52
  • in addition to below answers, in $http, do not use params. use like url: ``https://localhost:8000/api/test/${id}``, – Rishi0405 Mar 04 '19 at 14:58

3 Answers3

2

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

  • ...or this also can be done on controller or even at global level: https://spring.io/guides/gs/rest-service-cors/#_global_cors_configuration depending on how granular you expect restrictions should be – skyboyer Mar 04 '19 at 13:45
1

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.

Caius Cosades
  • 33
  • 1
  • 7
0

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.

hrvoj3e
  • 1,667
  • 1
  • 15
  • 16