This question already has answers here:
Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response
(27 answers)
Closed 6 years ago.
I'm using MEAN Stack User Registration and Login Example & Tutorial as the base for my app. It adds an auth header to every request in the run function:
$http.defaults.headers.common['Authorization'] = 'Bearer ' + $window.jwtToken;
I want to upload images to Cloudinary but I'm getting this error:
XMLHttpRequest cannot load https://api.cloudinary.com/v1_1/xxxx/upload. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
How can I remove this header specifically for requests to Cloudinary?
You will require an interceptor that checks for the url of the request and clears the header if it matches. alternatively you can use the $http config parameter.
Using the parameter:
$http.post('https://api.cloudinary.com/v1_1/' + someId + '/upload', data, { headers: {} });
Using an interceptor:
.factory('cloudinaryInterceptor', function() {
return {
request: function(config){
var authHeader = config.headers('authorization');
//Check for the host
var regex = /api\.cloudinary\.com/i;
if(regex.test(config.url))
//Detach the header
delete config.headers.authorization;
return config;
}
}
});
Remember to push the interceptor in the config phase
$httpProvider.interceptors.push('cloudinaryInterceptor');
This question has been asked before. The answer can be found here.
When you start playing around with custom request headers you will get a CORS preflight. This is a request that uses the HTTP OPTIONS verb and includes several headers, one of which being Access-Control-Request-Headers listing the headers the client wants to include in the request.
You need to reply to that CORS preflight with the appropriate CORS
headers to make this work. One of which is indeed
Access-Control-Allow-Headers. That header needs to contain the same
values the Access-Control-Request-Headers header contained (or more).
Related
This question already has answers here:
How does the 'Access-Control-Allow-Origin' header work?
(19 answers)
Closed 3 years ago.
I'm making a POST request to my API but getting returns a 'blocked by CORS policy' message.
The API is expecting a XML data which I have contained in a XML file which is being imported in to this request in the exampleAccountSettings value in the code example below.
The message I'm currently getting being returned from the API is this
Access to fetch at 'https://exampleAPI.com/api/settings/import' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
And here's my Promise
return new Promise((resolve, reject) => {
const requestUrl = https://exampleAPI.com/api/settings/import;
const init = {
method: 'POST',
mode: 'cors',
headers: {
authorization: localStorage.token,
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify(exampleAccountSettings)
};
return fetch(requestUrl, init).then((response) => {
log.debug('importAccountSettings(): response:', response);
})
});
All I've seen similar to this question state I need to add something like "Access-Control-Allow-Origin": "*" to specify that access is allowed but this seems to have no effect.
So is there a different approach for ES6 / React or maybe it's something I have misunderstood? Any advice welcome or if someone can point me in the direction of some research I'd be very appreciative!
You need to be able to control the server-side response headers from https://exampleAPI.com. If you don't own the domain or can't control the headers, then you're out of luck.
For security reasons, JavaScript can only make xhr calls to the same domain (or cross-domain if the right header Access-Control-Allow-Origin is present and allows your domain - or wildcard *).
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
I need to know Accept-Language request header value in order to make a translation on a page. I've tried to create an interceptor like
$httpProvider.interceptors.push(requestInterceptor);
, but in the method
request: function (config) {
of my interceptor I don't see Accept-Language header. I see Accept, Cache-Control, If-Modified-Since, Pragma but in the browser I do see Accept-Language.
Not all request headers are available in AngularJS request interceptor's config parameter. other header values are browser settings that are added while constructing the request.
You could use, but i'm not sure it gives you the right language.
var language = window.navigator.userLanguage or
window.navigator.language;
Only the server can see the value of Accept-Language. So i think the best way is to get this value from the server response-body and memorize it in you cookies (name example AcceptLanguageCookie) and after that you can overide the Accept-Language someway like this in your interceptor.
var app = angular.module("app", []);
app.config(["$httpProvider", function($httpProvider) {
// set Accept-Language header on all requests
$httpProvider.defaults.headers.common["Accept-Language"] = $cookies.get("AcceptLanguageCookie");
}]);
I see it isn't possible to edit headers with ngRessource after the service has been registered.
Isn't this a big problem for people using authentication via jwt tokens in the autorization header ?
I have to be able too set headers dynamically on each request :
{ Authorization: 'Bearer '+ myAuthService.getToken() }
It poses no problem what so ever with $http.
Is it really impossible to set tokens in the headers via ngRessource after the service has been registered ?
I have to be able too set headers dynamically on each request :
To set the header on each request, make the header a function:
{ Authorization: function(config) {
return 'Bearer '+ myAuthService.getToken();
}
}
From the Docs:
headers – {Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. Functions accept a config object as an argument.
By furnishing a function, the header value will be computed on each request.
I am having trouble with Restangular 1.4 sending authorization headers to an external web api, which challenges if no such header is provided.
In the following code I try to set the default headers to include basic auth header, but when I look at Fiddler it tells me that no authorization header is present from the start, so the api call is rejected as unauthorized.
Does anyone know if this a bug in Restangular, or whether there is something lacking in the way I have tried to code the auth header?
angular.module('MyAPIService', ['restangular']).factory('MyAPIService', function (Restangular) {
Restangular.setBaseUrl('http://mywebapi/api/');
var encoded = Base64.encode(username + ":" + password);
Restangular.setDefaultHeaders({ Authorization: 'Basic ' + encoded });
return Restangular.one('users', username).get();
Try to set headers in configuration block (not sure about factories). My code looks like this:
angular.module('app', ['restangular'])
.config(['RestangularProvider', function (RestangularProvider) {
// ... some code here
RestangularProvider.setDefaultHeaders({
token: 'some-secret-token'
// other headers
});
// ... some code here
}]);
and works for me.
Turns out that the issue is that the Authorization header is null for all preflight (i.e.) OPTIONS request. (to learn about them, see the section on Preflighted Requests at [https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS). So since I was able to control the API's Basic Auth handling, I made the API not issue a 401 challenge for such preflight requests. The Authorization header was present on non-preflight requests (GET,POST,PUT,DELETE).
I am using $http to make an api call which is sending some custom header like X-Foo. However I can't yet figure out how to read them. Inside the $http({...}).success(function (data, status, headers, config) {...}) function, headers is a function that should give me a hash of all headers but it only shows the header content-type. Is there a way to get the response headers ?
The custom headers will be visible in same domain. However, for the crossdomain situation, the server has to send Access-Control-Expose-Headers: X-Foo, ... header to make the custom headers visible.
Spring 4.0+ provide #CrossOrigin annotation which has following parameters
origins = list of Comma separated origin.
exposedHeaders = list ofcomma separated count custom parameters.
example
#CrossOrigin(origins = "*", exposedHeaders ="X-Total-Count")