2016-09-04 35 views
1

我在角发送POST请求到不同的域,像这样:Angularjs获得期权和POST请求

$http.post('http://domain.com/auth', { email: $scope.email, password: $scope.password }) 

而在我的请求日志,它只是发送OPTION请求。

所以我将此添加到我的domain.com/auth

header('Access-Control-Allow-Origin: *'); 
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); 
header('Access-Control-Allow-Methods: GET, POST, PUT'); 

但现在,我得到一个OPTION请求,然后再一个POST请求。所以,因为我的OPTION请求是第一个,我认为它仍然与我的结果混淆。

有谁知道如何获得POST请求而不是OPTIONS请求?

+0

根据[MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS):“浏览器”预检“请求,通过HTTP OPTIONS请求从服务器请求支持的方法方法,然后,在从服务器获得“批准”后,用实际的HTTP请求方法发送实际的请求并通知客户是否应该发送“凭证”(包括Cookies和HTTP认证数据)与请求。“ [见此](http://stackoverflow.com/a/13030629/2852427)和下面的答案。 – Ekin

回答

2

可以防止在POST预检通过触发simple request

要做到这一点,使用$httpParamSerializerJQLike编码数据(确保注入串行),并设置内容类型application/x-www-form-urlencoded

$http({ 
    url: 'YOUR_ENDPOINT', 
    method: 'POST', 
    data: $httpParamSerializerJQLike(YOUR_DATA), 
    headers: { 
    'Content-Type': 'application/x-www-form-urlencoded' 
    } 
}) 
+0

你摇滚的人,谢谢你。 – bryan