简体   繁体   English

AngularJS 和跨域 POST

[英]AngularJS and Cross Domain POST

i have a question regarding CORS requests with HTTP Authorization header:我有一个关于带有 HTTP 授权标头的 CORS 请求的问题:

It seems to me that web browser is not sending Authorization header with POST request, is there any way around this?在我看来,Web 浏览器没有通过 POST 请求发送 Authorization 标头,有什么办法可以解决这个问题吗?

Here is my Angular code:这是我的角度代码:

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

    app.controller('ctrl', function ($scope, $http) {
        $scope.insert = function () {

            $http.post('http://my.api.com/Insert',
                {
                    headers: {
                        'Authorization': 'Basic dGVzdDp0ZXN0',
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    data: {
                        'Code': 'test data'
                    },
                    withCredentials: true
                });
        };
    });

On server side i have this in my web.config在服务器端,我的 web.config 中有这个

<httpProtocol >
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With" />
    <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
    <add name="Access-Control-Allow-Credentials" value="true" />
  </customHeaders>
</httpProtocol>

You're using the $http.post incorrectly.您错误地使用了$http.post The second parameter is the data you need to send to server, you cannot set headers like this.第二个参数是你需要发送到服务器的数据,你不能像这样设置标题。 In your case, it will send the whole object as JSON payload在您的情况下,它会将整个对象作为JSON 有效负载发送

Try this:试试这个:

$http({
       url:'http://my.api.com/Insert',
       method:"POST",
       headers: {
                  'Authorization': 'Basic dGVzdDp0ZXN0',
                  'Content-Type': 'application/x-www-form-urlencoded'
       },
       data: {
              'Code': 'test data'
       }
  });

withCredentials - {boolean} - whether to to set the withCredentials flag on the XHR object. withCredentials - {boolean} - 是否在 XHR 对象上设置 withCredentials 标志。 See requests with credentials for more information.有关更多信息,请参阅带有凭据的请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM