简体   繁体   中英

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"
   }
})

在此处输入图片说明

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

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

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. Eg 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 (ie 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM