AngularJS and Cross Domain POST

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

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

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

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

回答1:

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

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


回答2:

withCredentials - {boolean} - whether to to set the withCredentials flag on the XHR object. See requests with credentials for more information.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!