AngularJS: POST Data to External REST API

前端 未结 3 752
渐次进展
渐次进展 2020-12-23 23:01

I have a basic AngularJS service setup like so:

app.factory(\'User\', function($resource) {
return $resource(\'http://api.mysite.com/user/:action:id/:attr\',         


        
3条回答
  •  长情又很酷
    2020-12-23 23:35

    Your two problems are actually one problem. The OPTIONS request is part of the CORS process. For POST requests, the browser first sends an OPTIONS call, and the server responds if it is okay to execute it.

    If the OPTIONS request fails, Angular / Chrome shows you the reason in the console. For example:

    OPTIONS https://*** Request header field Content-Type is not allowed by Access-Control-Allow-Headers. angular.min.js:106
    
    XMLHttpRequest cannot load https://***. Request header field Content-Type is not allowed by Access-Control-Allow-Headers. 
    

    You probably have to set Access-Control-Allow Headers on the server, too:

    header('Access-Control-Allow-Headers: Content-Type, x-xsrf-token')
    

    x-xrsf-token is for angular' to prevent CSRF. You may have to add more headers, depending on what you send from the client.

    Here is a very good guide on CORS: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

提交回复
热议问题