search

Home  >  Q&A  >  body text

angular.js - The same resource jquery cross-domain success $resource().save() failed

The jquery request is as follows:

The request for angularjs is as follows:

给我你的怀抱给我你的怀抱2820 days ago788

reply all(3)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-05-15 16:53:41

    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)

    reply
    0
  • 高洛峰

    高洛峰2017-05-15 16:53:41

    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.

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-15 16:53:41

    @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.

    reply
    0
  • Cancelreply