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);
});
Related
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);
});
I am new in socket.I have problem while using socket in my existing project.I have include socket.io.js file in my project and also create factory for using the socket. socket Request is going successfully from angular side.
I want to do when something is changed in my API response it automatically calls and show result in my page.So here is my code.I dont know how can i achieve this with socket
app.get('/ttms/getAlertsMessage/:customerid/:timstmp', getCookies, ttms.getAlertsMessage);// route
var socket = require('socket.io');
var io = socket.listen(server);
app.set('socketio', io);
io.on('connection', function (socket) {
console.log("==============connected=========")// this shows me connected
socket.on('test',function(data){
console.log(data)
})
});
Here is the node api which will call:
exports.getAlertsMessage = function(req, res, next) {
var customeruuid = req.param('customerid');
var start_time = new Date().getTime(),
request = require('request'),
api_url = global.common.base_url + 'ams/1.0.0/message/customeruuid/'+customeruuid;
var _m = new cLog.mObject('DELETE', 'deleteAllVNFBackup', api_url);
request({
url: api_url,
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': "Bearer " + req.cookies.apitoken
},
json: req.body
}, function(error, response, body) {
if (response.statusCode == 200 || response.statusCode == 201 || response.statusCode == 202) {
res.end(JSON.stringify(body));
} else {
res.send(response.statusCode, {
"error": JSON.stringify(body)
});
});
}
Here is the angular service:
GetUserSettings.getAlertsMessage($scope.customerId).then(function(data) {
var data1={"test":"test"};
socket.emit('test', data1);
socket.on('result', function (data) {
console.log(data)// gives json {"test":"test"};
});
})
can anyone give me some idea how can i achieve this.
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 upgraded my angularjs package to 1.6.3 and found out that the .success and .error functions got deprecated are removed. Now after using .then and .catch, only the .catch executes. I'm struggling to find out why the request fails this time around.
My initial working code was:
if ($scope.IsDinamicReport) {
$http({
method: "POST",
url: "/api/DynamicReport/Post?pageNumber=" + $scope.PageNum + "&orderbyColumn=" + $scope.orderByColumn + "&sortOrder=" + $scope.sortOrder
+ "&showNumberPagingStats=" + $scope.showNumberPagingStats,
contentType: "application/json",
data: $scope.report
}).success(function (result) {
angular.copy(result, $scope.dynamicReport);
if (!$scope.dynamicReport.Error) {
$scope.HideDynamicRepFunctions = false;
$scope.exportColumnSelected = $scope.dynamicReport.Columns[0]; //Set default for export drop down
//TABLE SIZING
var persentage = $scope.returnTableSizing(result.Columns.length);
$('[data-table=container]')
.css('margin-left', '25px')
.css('padding-right', '25px')
.css('width', persentage)
.css('max-width', persentage);
}
else
alert("Error occured while generating the report, please contact helpdesk.");
}).error(function (data) {
alert("An error occured while generating the report, please try again.");
});
}
and then I changed it to the following:
if ($scope.IsDinamicReport) {
$http({
method: "POST",
url: "/api/DynamicReport/Post?pageNumber=" + $scope.PageNum + "&orderbyColumn=" + $scope.orderByColumn + "&sortOrder=" + $scope.sortOrder
+ "&showNumberPagingStats=" + $scope.showNumberPagingStats,
contentType: "application/json",
data: $scope.report
}).then(function (result) {
angular.copy(result, $scope.dynamicReport);
if (!$scope.dynamicReport.Error) {
$scope.HideDynamicRepFunctions = false;
$scope.exportColumnSelected = $scope.dynamicReport.Columns[0]; //Set default for export drop down
//TABLE SIZING
var persentage = $scope.returnTableSizing(result.Columns.length);
$('[data-table=container]')
.css('margin-left', '25px')
.css('padding-right', '25px')
.css('width', persentage)
.css('max-width', persentage);
}
else
alert("Error occured while generating the report, please contact helpdesk.");
}).catch(function (data) {
alert("An error occured while generating the report, please try again.");
});
}
How do I go about debugging what went wrong if you cannot see the error here already? The only thing I changed there is just the deprecated functions
Use the standard .then and .catch promise methods instead, but note that the method signatures and return values are different:
Before:
$http(...)
.success(function onSuccess(data, status, headers, config) {
// Handle success
//...
}).error(function onError(data, status, headers, config) {
// Handle error
//...
});
After:
$http(...)
.then(function onSuccess(response) {
// Handle success
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
//...
return <some value>;
}).catch(function onError(response) {
// Handle error
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
//...
throw <some error>;
});
For more information, see AngularJS Developer Guide - Migrating from 1.5 to 1.6
In the case of your code, the result value is a property of the response object:
$http({
method: "POST",
url: "/api/DynamicReport/Post?pageNumber=" + $scope.PageNum + "&orderbyColumn=" + $scope.orderByColumn + "&sortOrder=" + $scope.sortOrder
+ "&showNumberPagingStats=" + $scope.showNumberPagingStats,
contentType: "application/json",
data: $scope.report
//}).success(function (result) {
}).then(function (response) {
//RESULT is a property of response
var result = response.data;
angular.copy(result, $scope.dynamicReport);
if (!$scope.dynamicReport.Error) {
$scope.HideDynamicRepFunctions = false;
$scope.exportColumnSelected = $scope.dynamicReport.Columns[0]; //Set default for export drop down
//TABLE SIZING
var persentage = $scope.returnTableSizing(result.Columns.length);
use debugger; in your source code .
press F12 , F8 , F10 .it will help
From the angular doc the $http service return a promise that has two callback, of success and of failure (no catch method).
In your code you're trying to handle the rejection with a catch, but this is not reported in the doc.
This is the syntax provided, try to modify your code accordingly.
$http({
method: 'GET',
url: '/someUrl'
}).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.
});
source: https://docs.angularjs.org/api/ng/service/$http
i am new to breeze and odata..
im trying to fetch data from odata api using breeze in angular...
heres my code:
//adding authorization to the header
var authObj = localStorageService.get('authorizationData');
var token = 'Bearer ' + authObj.token;
var oldClient = OData.defaultHttpClient;
var myClient = {
request: function (request, success, error) {
request.headers.Authorization = token;
return oldClient.request(request, success, error);
}
};
OData.defaultHttpClient = myClient;
baseService.getBreezeAdapter;
breeze.NamingConvention.camelCase.setAsDefault();
var manager = baseService.newManager();
var query = new breeze.EntityQuery()
.from('Customers');
function fetchData() {
manager.executeQuery(query)
.then(function (data) {
console.log(data)
})
.catch(function (fail) {
console.log(fail)
})
.finally(function (response) {
});
};
when i look into fiddler.. there was no error..its working fine..
but after the query it falls down to catch which is fail.. it returns an error message
"; ", but it said that the statustext is ok and it has the data in its body element..
here is the actual error
{message: "; ", statusText: "OK", status: 200, url: "http://xxxxxx.net/odata/Customers", body: Object…}
can someone can explain to me why its returning an error ";"