AngularJS HTTP Post请求中断失败

问题描述:

我一直在开发一个自定义PHP REST端点以与其他4个系统捆绑在一起,以及一个前端应用程序通过GET和POST与Endpoint进行通信。 API和Frontend应用程序都位于不同的域(systemapi.local和app.local,分别没有立即计划将它们移动到一个域中)。AngularJS HTTP Post请求中断失败

我有一个AngularJS调用到一个POST请求的端点之一,本质上是做一个登录来获得一个活动的会话。除了该方法本身运行POST请求外,基于Chrome的网络输出,我的浏览器显然没有POST请求。

我发送POST请求的方式有点奇怪,因为我在x-www-form-urlencoded中发送了一个urlencoded JSON对象。从下面的代码块闪烁应该很容易。

//Runs on app.local/index.html 
var app = angular.module("FizzBuzzGate", []); 

/* Config */ 
app.config(['$httpProvider', function ($httpProvider) { 
    //Reset headers to avoid OPTIONS request (aka preflight) 
    $httpProvider.defaults.headers.common = {}; 
    $httpProvider.defaults.headers.post = {}; 
    $httpProvider.defaults.headers.put = {}; 
    $httpProvider.defaults.headers.patch = {}; 
}]); 

app.config(['$sceDelegateProvider', function($sceDelegateProvider) { 
    $sceDelegateProvider.resourceUrlWhitelist([ 
     'self', 
     'http://systemapi.local:9001/**', 
     'http://systemapi.local/**' 
    ]); 
}]); 

/* Controllers */ 
app.controller('FizzBuzzGateLogin', function ($scope, $http) { 
    $scope.login = function() { 
    var username = document.getElementById("login_username").value; 
    var password = document.getElementById("login_password").value; 

    requestData = {}; 
    requestData.method = "login"; 
    requestData.data = '{"username":"'+username+'"},{"password":"'+password+'"}'; 
    requestData.dataStr = "method="+requestData.method+"&input_type=json&response_type=json&data="+encodeURIComponent(requestData.data); 

    $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded"; 

    if(Boolean(username) && Boolean(password)) { 
     $http.post('http://systemapi.local:9001/api/login', requestData.dataStr).success(function(data, status, headers) { 
      alert("Request Success!"); 
     }).error(function(data, status, headers) { 
      alert("Error: " + headers); 
     }); 
    } else { 
     alert("Fields not populated, please check your fields and try again."); 
    } 
    }; 
}); 

/* Directives */ 
app.directive("loginForm", function() { 
    return { 
     restrict: 'E', 
     replace: false, 
     templateUrl: "js/templates/login.html" //Basically implements a login form, nothing significant 
    }; 
}); 

在REST API,我必须在每次调用所做的标题显式声明CORS设置:

header("Access-Control-Allow-Credentials: true"); 
header("Access-Control-Allow-Orgin: *"); 
header("Access-Control-Allow-Headers: Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With"); 
header("Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS"); 
header("Content-Type: application/json"); 
header("X-API-Provider: FizzBuzzEnterprises"); 

尽管如此,角永远不能发送成功的POST调用域。我不知道为什么。我在我的应用程序中进行了更改,以确保我可以根据我在Stack Exchange上所做的研究来做到这一点。我的代码中缺少哪些可以解决此问题的内容?

+0

浏览器JavaScript控制台日志中的任何错误? –

这个问题其实并没有在我的头文件中设置CORS。我拼写错了“Origin”。解决这个问题,解决了这个问题。