AngularJS: POST Data to External REST API

前端 未结 3 715
渐次进展
渐次进展 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

    0 讨论(0)
  • 2020-12-23 23:39

    In AngularJS to make CORS working you also have to overwrite default settings of the angular httpProvider:

    var myApp = angular.module('myApp', [
        'myAppApiService']);
    
    myApp.config(['$httpProvider', function($httpProvider) {
            $httpProvider.defaults.useXDomain = true;
            delete $httpProvider.defaults.headers.common['X-Requested-With'];
        }
    ]);
    

    Just setting useXDomain to true is not enough. AJAX request are also send with the X-Requested-With header, which indicate them as being AJAX. Removing the header is necessary, so the server is not rejecting the incoming request.

    Note: Answer only works for older AngularJS version previous to 1.2. With 1.2 and above you don't have to do do anything to enable CORS.

    0 讨论(0)
  • 2020-12-23 23:40

    Better to solve this problem at the server. On apache you can solve it like this in a .htaccess file. This is a source of pain for angular development and can be solved in angular as well but its probably not the best way to do it.

    Header set Access-Control-Allow-Origin "*"
    Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
    Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
    
    0 讨论(0)
提交回复
热议问题