I have download text file request from backend. I need to download the file by posting get request given in service.js but the problem is I am getting %7d %7d in blank when I am downloading the file. Need assistance.I even tried with ng-href, still no luck
HTML:
<button class="btn btn-info" ng-click="downloadAllExhibitors();">
Download</button>
JS:
$scope.downloadAllExhibitors = function () {
$scope.newFile = service.downloadExhibitor();
}
Service.js
var url =' http://localhost/1290/';
function downloadExhibitor() {
var token = 129821sahh;
var auth = "Token" + ' ' + token;
var config = {
headers: {
'Content-Type': 'application/json',
'Authorization': auth
}
}
return $http.get(url + 'entity/campaigns/download_exhibitors/', config);
}
The problem with your code lies in
$scope.newFile = service.downloadExhibitor(); Since $http.get is async and returns a promise, you can always define callbacks to handle the success/error response from server.
So, by the time your server returns the response you have no actions defined to handle it. Your service can be re-written as :-
var url =' http://localhost/1290/';
function downloadExhibitor() {
var token = 129821sahh;
var auth = "Token" + ' ' + token;
var config = {
headers: {
'Content-Type': 'application/json',
'Authorization': auth
}
}
return $http.get(url + 'entity/campaigns/download_exhibitors/', config)
.then(successHandler, errorHandler);
}
function successHandler(response){
/* we've got file's data from server */
return response.data;
}
function errorHandler(error){
/* we've got error response from server */
throw new Error('ERROR ' + error);
}
and eventually the service invocation
$scope.newFile = "";
service.downloadExhibitor()
.then(function(data){
$scope.newFile = data;
}, function(error){
console.log(error);
});
Related
$scope.newFile is my response from backend. Actually my response should be a text file, which is working in postman.But in browser , I am getting
Cannot GET
/Organizer/%7B%22data%22:%22id/tname/temail/tphone/twebsite/tvenue/ttags/n83/tAny%20Name/ta#b.com/t9009009009/thttp://www.anyname.com/tHall%20A/ttag1,%20tag2,%20tag3/nsunitha/tsunitha#gmail.com/t55555541/thttp://www.sunitha.com/nSuhasini/tsuha#gmail.com/t955555544/thttp://www.suha.com/nRaichel/traichel#gmail.com/t955548458/thttp://www.raichel.com/n%22,%22status%22:200,%22config%22:%7B%22method%22:%22GET%22,%22transformRequest%22:[null],%22transformResponse%22:[null],%22jsonpCallbackParam%22:%22callback%22,%22headers%22:%7B%22Authorization%22:%22Token%2013946cc6c575d61b042b01b6905f1d239b3d9b08%22,%22Accept%22:%22application/json,%20text/plain,%20*/*%22%7D,%22url%22:%22http://http://localhost/1290//entity/campaigns/download_exhibitors/%22%7D,%22statusText%22:%22OK%22,%22xhrStatus%22:%22complete%22%7D
Service.js
var url =' http://localhost/1290/';
function downloadExhibitor() {
var token = 129821sahh;
var auth = "Token" + ' ' + token;
var config = {
headers: {
'Content-Type': 'text/plain',
'Authorization': auth
}
}
return $http.get(url + 'entity/campaigns/download_exhibitors/', config)
.then(successHandler, errorHandler);
}
function successHandler(response){
/* we've got file's data from server */
return response.data;
}
function errorHandler(error){
/* we've got error response from server */
throw new Error('ERROR ' + error);
}
and eventually the service invocation
JS:
$scope.newFile = "";
service.downloadExhibitor()
.then(function(data){
$scope.newFile = data;
}, function(error){
console.log(error);
});
HTML:
<button class="btn" ng-click="downloadAllExhibitors();">
<a ng-href="{{newFile}}" target="_blank">Download</a></button>
You can try below code in controller...
var file = new Blob([data], {
type : 'text/plain'
});
if (navigator.userAgent.indexOf('MSIE') !== -1
|| navigator.appVersion.indexOf('Trident/') > 0) {
window.navigator.msSaveOrOpenBlob(file);
} else {
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
Following code in controller made my work simple , and it downloaded the file finally.
var file = new Blob([data], {
type: 'text/plain'
});
if (navigator.userAgent.indexOf('MSIE') !== -1 ||
navigator.appVersion.indexOf('Trident/') > 0) {
window.navigator.msSaveOrOpenBlob(file);
} else {
var a = window.document.createElement("a");
a.href = window.URL.createObjectURL(file, {
type: "text/plain"
});
a.download = "filename.csv";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
Hello I want to use external API to gather all the current currency rate. My front is based on token and I am storing token in localForage which is nothing but async localStorage.
//this execute after every page refresh
$localForage.getItem('authorization')
.then(function(authData) {
if(authData) {
$scope.authentication.isAuth = true;
$http.defaults.headers.common.Authorization = 'Bearer ' + authData.token;
//set authentication variable to true and add token to every request after page refresh
}
}, function(){
console.log("error with getting authorization localForage after refresh");
}
);
//this execute after custom event emitted after success login response
$rootScope.$on('localForageUpdated', function(event){
$localForage.getItem('authorization')
.then(function(authData) {
if(authData) {
$http.defaults.headers.common.Authorization = 'Bearer ' + authData.token;
$scope.authentication.isAuth = true;
//set authentication variable to true and add token to every request after page refresh
} else {
$scope.authentication.isAuth = false;
}
}, function(){
console.log("error with getting authorization localForage on event");
}
);
});
So this basically add header with token before every backend request.
Unfortunately when I try to download all the current currency rate from external API I get following error:
Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
That's due to fact I added header with my token. Can I somehow add an exception while seting $http.defaults.headers.common.Authorization = 'Bearer ' + authData.token;?
Here is my solution you can use it to inspire you.
I create au interceptor to add the authorization. In this interception you can put your exception logic base on your need in my case I base it on the url.
angular.module('yourAppName').factory('authInterceptor', function ($q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.localStorage.token
&& $window.localStorage.token !== undefined
&& $window.localStorage.token !== 'undefined') {
if(config.url.startsWith("xyz")){
delete config.headers.Authorization;
} else {
config.headers.Authorization = 'Bearer ' + $window.localStorage.token;
}
}
return config;
},
response: function (response) {
return response || $q.when(response);
},
// optional method
responseError: function (response) {
return $q.reject(response);
}
};
});
angular.module('rmsApp').config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});
I am able to make REST API call using Postman/browser by passing Authorization token. However when I make the same call using AngularJS it's getting errored out. It's returning net::ERR_INSECURE_RESPONSE
I would like to know what can be possibly causing this error and how to fix this.
$http.get('https://hostname:8443/medrecdb-records', {
headers: {
'Authorization': 'Basic YWRtaW46UGFzc3dvcmQx' }})
.then(function (response) {
$scope.drug = response.data;
console.log("Response is: " + response);
}).catch(function (response) {
// Handle error
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
console.log("Response data is: " + data);
});
I am newbie of angularJS. I want to add header in my http request but i am not understanding how? so far i've written this code.
Original code without header:
function saveUser(user, $http) {
var token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjYxLCJpc3MiOiJodHRwOlwvXC8zNC4yMDQuMjIyLjExM1wvYXBpXC91c2VycyIsImlhdCI6MTQ5NTE4MDY3MCwiZXhwIjoxNDk1MTg0MjcwLCJuYmYiOjE0OTUxODA2NzAsImp0aSI6IkdkNXdUSmZQMDRhcjc2UWIifQ.dKGZTysAibFbtruvSI7GwFV61kh43CX22g8-sRV9roQ";
var url = __apiRoot + "/users/" + user.id;
var dataObj = {
payload: JSON.stringify(user),
_method: "PUT",
}
return $http.post(url, dataObj);
}
Now i am adding header to it, the code becomes like this:
function saveUser(user, $http) {
var token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjYxLCJpc3MiOiJodHRwOlwvXC8zNC4yMDQuMjIyLjExM1wvYXBpXC91c2VycyIsImlhdCI6MTQ5NTE4MDY3MCwiZXhwIjoxNDk1MTg0MjcwLCJuYmYiOjE0OTUxODA2NzAsImp0aSI6IkdkNXdUSmZQMDRhcjc2UWIifQ.dKGZTysAibFbtruvSI7GwFV61kh43CX22g8-sRV9roQ";
var url = __apiRoot + "/users/" + user.id;
var dataObj = {
payload: JSON.stringify(user),
_method: "PUT",
}
return $http({headers: {
'Authorization': token
}}).post(url, dataObj);
}
By adding header, i am getting this error:
angular.js:14525 Error: [$http:badreq] Http request configuration url
must be a string or a $sce trusted object. Received: undefined
You're using the wrong syntax. Take a look at the angular documentation for $http here.
Your code should look like this:
$http({
method: 'POST',
url: __apiRoot + "/users/" + user.id,
data: JSON.stringify(user)
headers: {
'Authorization': token
}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
I am trying to send token in the header but it is not working, what is the way of sending token in the header? Or what is the problem in my code?
return $q(function(resolve , reject){
var token = StorageService.getToken();
if(!token)
console.log('no token')
var resource = $resource(usersAPI.profile,null,
{
query: {
method: 'GET',
header: {
'Authorization': 'Bearer ' + token
}
}
})
var profile = resource.query(function(result){
console.log(result)
},function(err){
console.log('error',err)
})
resolve(profile)
})