AngularJS and Cross Domain POST
35,488
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'
}
});
Author by
aron
Full stack software developer. In day to day work using these technologies: C#, ASP.NET, SQL, JavaScript, TypeScript, AngularJS
Updated on July 09, 2022Comments
-
aron almost 2 years
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
<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>
-
aron over 10 yearsThats it, thanks! Just one more thing i had to fix is that you cannot use withCredentials: true if you have Access-Control-Allow-Origin:*
-
Khanh TO over 8 years@Veshraj Joshi: What is your case?
-
Dezmen Ceo Sykes over 8 yearsso the Basic dGVzdDp0ZXN0 part, whtas that about? is the ' dGVzdDp0ZXN0' code mandatory?
-
Veshraj Joshi over 8 years@khanh To i am trying to make html files on local machine with angular js and on domain laravel 5.1(php framework); and works fine if html files are on same domain; otherwise didnot work, but amazing thing is that "get " method works fine from everywhere with above code.
-
Khanh TO over 8 years@Dezmen Ceo Sykes: the ' dGVzdDp0ZXN0' code is mandatory: en.wikipedia.org/wiki/Basic_access_authentication . But it should have different value based on current user.
-
Khanh TO over 8 years@Veshraj Joshi: it's weird to me when you said the "get" ajax request works fine everywhere (even for cross-domain). Is CORS enabled on your server? developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS