angular.js - The same resource jquery cross-domain success $resource().save() failed
给我你的怀抱
给我你的怀抱 2017-05-15 16:51:41
0
3
743

The jquery request is as follows:

The request for angularjs is as follows:

给我你的怀抱
给我你的怀抱

reply all(3)
伊谢尔伦

Look carefully at the difference in the request between your two requests. I am talking about the content-type part. The default content-type of jquery is application/x-www-form-urlencoded, which is a simple request and does not require preflight. (This is the options request in the second picture). The default content-type of angular's post request is application/json. This is a complex request, mainly for preflight. But since you encounter an error, it means that your backend does not handle the options situation. Two solutions:

  1. Manually set the header for your angular resource service and change the content-type to application/x-www-form-urlencoded. (Not sure if resources can customize the header, because resources are actually standard restful services)

  2. Requires your back-end program to make corresponding modifications to enable it to handle complex requests (actually very small changes, whether java, python or ruby ​​on rails have ready-made solutions)

小葫芦

Please note that when you use jquery to send a request, the response headers are set to Access-Control-Allow-Origin, so you can cross domains;
But when you send it with Angular, this header is not there. It should be that your server-side response logic has made some judgment, causing this header to not be set normally.

phpcn_u1582

@Evian It’s not that Angular thinks preflight is needed, but that the browser thinks (due to Angular’s ​​configuration of HTTP requests, Content-TypeCache-Control, according to MDN documentation) that preflight needs to be initiated.

@YAN_YANG Judging from the response header, your server allows preflight requests. You can delete this from the server. I’m not sure how you configured CORS. For example, there is a similar setting in Apache:

Header set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

Removing the OPTIONS option can directly avoid responding to preflight. Of course, it is correct for you to handle it reasonably. (See: http://stackoverflow.com/questions/23954433/post-request-with-angularj...)

Also, have you set the correct request headers on Angular? (for CORS)

http://chstrongjavablog.blogspot.sg/2013/04/enabling-cors-for-jetty.ht...

This article explains the various problems with OPTIONS and why jQuery is fine (HEADER is specifically removed for CORS). There is also a Java CORS implementation and the setting of HEADER during requests. How to set up Angular? Just check the documentation of $httpProvider.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template