js
what I'm trying to do is making REST API REQUEST to server.
A request should be 'GET' method and include 'Authorization' header.
my factory code which communicate REST server is like this 'use strict';
angular.module('mabidualApp')
.factory('User', function ($resource, config) {
return $resource(config.API+':url/:id', {
url: '@url', id: '@id'
}, { //parameters default
auth: {
method: 'POST',
params: {
url: "token",
}
},
get: {
method: 'GET',
headers:{'Authorization':'Bearer oLDMYrJD0Qg15Nhv7N-H6w'} ,
params: {
url:"users",
id:'me'
}
}
});
the fitst problem is here
headers:{'Authorization':'Bearer oLDMYrJD0Qg15Nhv7N-H6w'} ,
If I add header the method changes to 'OPTIONS' not 'GET'. I found out it's about CORS preflight something, but I couldn't figure it out how to disable it..
so I tried to change my configuration in app.js
.config(function($locationProvider, $routeProvider, $httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$httpProvider.defaults.headers.get['Authorization'] ='Bearer oLDMYrJD0Qg15Nhv7N-H6w';
the second problem is here
$httpProvider.defaults.headers.get['Authorization'] ='Bearer oLDMYrJD0Qg15Nhv7N-H6w';
It makes the error below.
Cannot set property 'Authorization' of undefined
Is there any solution to send A 'GET' request with 'Authorization' header? thanks
I think you're using params in the wrong way in your get request. Try switching params and headers like that :
angular.module('mabidualApp')
.factory('User', function ($resource, config) {
return $resource(config.API+':url/:id', {
url: '@url', id: '@id'
}, { //parameters default
auth: {
method: 'POST',
params: {
url: "token",
}
},
get_auth: {
method: 'GET',
params: {
url:"users",
id:'me'
},
headers: {'Authorization':'Bearer oLDMYrJD0Qg15Nhv7N-H6w'}
}
});
I changed your custom get request because 'get' might be defined by angular already, but I'm not sure :
$httpProvider.defaults.headers.get_auth['Authorization'] ='Bearer oLDMYrJD0Qg15Nhv7N-H6w';
Besides, are you sure you don't need any other headers?