I'm using angularJS to call a restfull API in symfony 2.
My angularJS app url is angular.me.dev
My symfony2 api url is api.me.dev
I followed this tutorial to make my restfull api.
The problem is when I try to call this api
$http.({
method: 'GET',
url: 'http://api.me.dev/api/articles',
headers: {
'Authorization': 'Bearer ' + token
}
})
An error occured: (here on google chrome):
XMLHttpRequest cannot load http://api.me.dev/api/articles. Response for preflight has invalid HTTP status code 405
(and on on firefox):
The Same Origin Policy disallows reading the remote resource
what did I find about this ?
AngularJS Sends OPTIONS request instead of POST
AngularJS performs an OPTIONS HTTP request for a cross-origin resource
Then I decide to allow headers, origin, ... on my server like this:
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Credentials "true"
Header always set Access-Control-Allow-Methods "PUT, DELETE, POST, GET, OPTIONS"
Header always set Access-Control-Allow-Headers "*"
No change
I add to AngularJS
#coffee script
app.config ['$httpProvider', ($httpProvider) ->
$httpProvider.defaults.useXDomain = true
delete $httpProvider.defaults.headers.common['X-Requested-With']
]
Then I decided to install NelmioCorsBundle in my symfony api but I didn't see any change.
Finally, I notice a call works
$http.({
method: 'GET',
url: 'http://api.me.dev/api/articles',
})
Here the call return a 401 response (good, i need to be logged)
$http.({
method: 'GET',
url: 'http://api.me.dev/public/api/users',
})
Here I have a call doesn't need authorization, it works.
I found only when I remove headers it works, and when I had any headers (content-type or authorization for example) an error occured.
Can anyone help me ? thanks !
Ok, my bad.
I said NelmioCors seems not working but i did something wrong.
I try again with nelmio cors bundle, using this configuration.
nelmio_cors:
paths:
'^/':
allow_origin: ['http://angular.me.dev']
allow_headers: ['Authorization', 'X-Requested-With', 'Content-Type', 'Accept', 'Origin', 'X-Custom-Auth']
allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']
max_age: 3600
It's working !
NelmioCorsBundle resolve the problem.
https://github.com/nelmio/NelmioCorsBundle
Related
So I have a simple axios request from my reactjs component:
let config = {headers: {'Authorization': 'Bearer token-value'}};
axios.get(routes.API + '/user', config).then(response => {
console.debug(response);
}).catch(error => {
// error
});
Backend is just a simple symfony controller that accepts GET request and should return user data.
The issue is that this request only makes OPTIONS request. And it fails because my backend function is only supposed to accept get. It fails because of method not allowed. If I allow OPTIONS request method it fails, because of authorization error. And I never want to authorize OPTIONS because it would fetch user from the database.
Also it never does GET request.
If I remove config object and only leave url the request works as it should and never sends OPTIONS request, but I need header to pass my authorization token.
I have these headers enabled on my backend nginx server:
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Headers' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
What am I missing here?
That's not really an axios specific behaviour, you should make sure that your server is able to handle CORS properly. For Symfony - there is a bundle that does it for you, I had to use it when having a similar issue:
https://github.com/nelmio/NelmioCorsBundle
Here is a sample config:
nelmio_cors:
defaults:
allow_credentials: false
allow_origin: []
allow_headers: []
allow_methods: []
expose_headers: []
max_age: 0
hosts: []
origin_regex: false
forced_allow_origin_value: ~
paths:
'^/api/':
allow_origin: ['*']
#Without this the OPTIONS request by axios won't work
allow_headers: ['Content-Type']
allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
max_age: 3600
Call from Ionic app using $http GET to Wordpress REST API is failing with error:
XMLHttpRequest cannot load http://mywordpressdomain.com/wp-json/wp/v2/categories. Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.
I noticed that request header has:
Access-Control-Request-Headers:token
I tried removing the header in my $http get request.
$http({
method: 'GET',
url: url,
headers: { 'Access-Control-Request-Headers': undefined },
})
But the Access-Control-Request-Headers: token is still present in the request header. Seems like headers has no effect.
How can I fix this?
for not having any CORS issue related with http request on your localhost while developing set skipAuthorization: true... just do like this:
'$http({
method: 'GET',
url: 'http://yoururl.com/yourrequest',
skipAuthorization: true
})'
I am making a web app using angularjs. I am making request on elasticsearch api. This is the code:
app.controller('usersDatas', function($scope, $http){
$http.post("http://192.168.6.55:9200/userdata/_search", {headers : { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
data: "{ 'query': { 'query_string': { 'query': 'png' } } }"
// Access-Control-Allow-Origin: true
}).success(function(data){
console.log(data);
});
});
This is error I have :
XMLHttpRequest cannot load http://192.168.6.55:9200/userdata/_search. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.
I have added this :
http.cors:
enable: true
allow-origin: /https?:/\/\/localhost(:[0-9]+)?/
to my elasticsearch (/etc/elasticsearch/elasticesarch.yml) config. I don't know if the problem comes from elasticsearch or from angularjs.
How can I solve this ?
Thanks.
You must add in HEADER Access-Control-Allow-Origin
PHP Example:
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
This is browser issue First close all the chrome browser windows ...
open terminal
sudo -i
(Your Password)
then type
google-chrome --disable-web--security
Then try the link in that url
I have implemented a backend with an Apache server with AMI from AWS and Laravel. For authentication I use the JWT Auth plugin.
My frontend is build with AngularJS. Before using the authentication everything worked fine. When I try to authenticate the user with an authorization header I get a CORS Preflight error. I use the following call from my AngularJS application:
delete $http.defaults.headers.common['X-Requested-With'];
$http.defaults.headers.common.Accept = "text/plain";
$http({
url: 'http://MYURL',
method: "GET",
headers: {
'Access-Control-Allow-Headers': 'Authorization, Content-Type, Accept',
'Content-Type' : 'text/plain',
'Authorization': 'Bearer '+token,
}
})
In my Laravel backend I used the following configuration:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Authorization, Content-Type");
This is the response from the OPTIONS call:
This is the error I get in Google Chrome:
Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
Any ideas on this issue? Do I have to configure this within Angular, Laravel or my httpd.conf?
EDIT:
I added it as a global Middleware and in the app.php as service provider.
The configuration looks like this:
return [
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['Authorization, Content-Type'],
'allowedMethods' => ['*'],
'exposedHeaders' => [],
'maxAge' => 0,
'hosts' => [],
];
But I have no idea if it works correctly.
Have you considered using a plugin for managing CORS setup like this one?
It appears that the list of headers you allow on the server side (Authorization, Content-Type) is not the same as the list of headers being sent by the request (Authorization, Content-Type, Accept). It could be that the front end is asking for permissions that you aren't allowing on the back end.
As the title suggest, I need to pass an authorization token but when I check the network console, I'm getting a 403 because the accept and authorization isn't there. NOTE: I removed my authorization token for this example
$http({
url: 'http://api.stubhub.com/search/catalog/events/v2?title="san"',
dataType: 'json',
method: 'GET',
data: '',
headers: {
"Content-Type": 'application/json',
"Authorization": 'Bearer {token}'
}
}).success(function(response){
$scope.searchResponse = response;
}).error(function(error){
$scope.error = error;
});
This seems like correct syntax? What's wrong here?
EDIT: added the XHR screenshot
EDIT: 2. Here's my network traffic, HAR via paste bin:
http://pastebin.com/fiFngZSy
setting custom headers on XHR requests triggers a preflight request.
I bet you're seeing an OPTIONS request without the Authorization header, and a corresponding response whose Access-Control-Allow-Headers header value is not listing Authorization, or the API doesn't even allow unauthorized OPTIONS requests.
I don't know the stubhub api, but does it return CORS-compliant responses?