AngularJS 和跨域 POST [英] AngularJS and Cross Domain POST

查看:37
本文介绍了AngularJS 和跨域 POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于带有 HTTP 授权标头的 CORS 请求的问题:

i have a question regarding CORS requests with HTTP Authorization header:

在我看来,网络浏览器没有通过 POST 请求发送 Authorization 标头,有什么办法可以解决这个问题吗?

It seems to me that web browser is not sending Authorization header with POST request, is there any way around this?

这是我的 Angular 代码:

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
                });
        };
    });

在服务器端,我的 web.config 中有这个

On server side i have this in my 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>

推荐答案

您错误地使用了 $http.post.第二个参数是您需要发送到服务器的数据,您不能像这样设置标题.在您的情况下,它将发送整个对象作为 JSON 负载

You're using the $http.post incorrectly. 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

试试这个:

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

这篇关于AngularJS 和跨域 POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆