Http request in angular send undefine values - angularjs

** It turns out that the problem was at the server **
I'm trying to excute HTTP post request (from my angular client) to my server (node express). The server recive the request but the data is undefined.
Already tried to make this req by postman and it worked perfect there.
var req = {
method: 'POST',
url: _url +'/login',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: { user: 'someUser', password :'somePass' }
}
$http(req)
.then(function success(res){
...
}, function error(res){
...
});

You are sending JSON data and sending the header of x-www-form-urlencoded.
Change the content type to "application/json"
Like:
headers: {
'Content-Type': 'application/json'
}

Related

Cannot generate embed token using access token in power bi

I'm trying to be understand authorization mechanism in power bi API
I would embed a report in my web app.
I have done the steps as mentioned in docs
Actually I would get report embedded url then use power bi JS API to embed the report.
Getting access_token is successful
var options = {
'method': 'POST',
'url': `https://login.microsoftonline.com/${process.env.TENANT_ID}/oauth2/token`,
'headers': {
'Content-Type': 'multipart/form-data'
},
formData: {
'grant_type': process.env.GRANT_TYPE,
'client_id': process.env.CLIENT_ID,
'client_secret': process.env.CLIENT_SECRET,
'resource': "https://analysis.windows.net/powerbi/api",
'Scope': "https://analysis.windows.net/powerbi/api/.default"
}
};
Now I try to get embedded token for report in group
var data = { accessLevel: "View", datasetId: "5b11d62a-803e-46c9-83f3-*****" };
var config = {
method: 'post',
url: `https://api.powerbi.com/v1.0/myorg/groups/${process.env.GROUP_ID}/reports/${process.env.Report_ID}/GenerateToken`,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${JSON.parse(response).access_token}`
},
data: data
};
let embedtoken
try {
embedtoken = await axios(config)
}
catch (e) {
console.log(e)
}
context.res = {
// status: 200, /* Defaults to 200 */
body: JSON.parse(response).access_token
};
I get error 400 response
But When I generate an embed token for dashboard I get a valid token. But of course that's not working with get report API
My goal is to get report infos. For information I get get that using the access token but it's not safe
For POST API requests, data should be passed in string format. This can be done by using for example, JSON.stringify(data).
Refer below code snippet which should resolve the error.
var config = {
method: 'post',
url: `https://api.powerbi.com/v1.0/myorg/groups/${process.env.GROUP_ID}/reports/${process.env.Report_ID}/GenerateToken`,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${JSON.parse(response).access_token}`
},
data: JSON.stringify(data) };

Sending POST request weird issue

I'm quite new with ANGULAR and web development in general and I'm currently working on a web tool. Now I want this tool to send a POST request to a web service but Im encountering a weird bug. Now I have below code in my javascript:
var data_info = { test_id: 'TEST', model_id: 'TEST:TEST_ID' };
//data_info = JSON.stringify(data_info);
var request_json = {
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
data: data_info,
cache: false,
};
console.log(request_json);
$http(request_json).then(function successCallback(response) {
// response code here
}
Now this code currently doesn't pass the preflight request check and is always returning a 405. But if I change the line data: data_info in the request JSON into a new key let's say body: data_info it now successfully sends the request and I can confirm that the service is receiving it. I'm not sure what's the issue here and can't figure it out.
change your header to :
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
Please try

CORS post call not working in Angularjs

I am trying to implement cross-origin post call from angularjs application, then I get the following error.
Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
But, when I make a Ajax call it works properly.
How HTTP post call work in angularjs?
Ajax call
$.ajax({
type: 'POST',
url: getAccessTokenUrl,
data: JSON.stringify(clintdata),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resultData) {
console.log(resultData);
},
error: function (request, status, error) {
console.log(status);
}
});
Angularjs HTTP call
$http({
method: 'POST',
url: getAccessTokenUrl,
data: clientdata,
headers: {
'Authorization': undefined,
'Auth-Token': undefined
}
}).then(function(res){
console.log(res);
}, function(err){
console.log(err);
});
I have some default setting. Authorization is for others REST
$http.defaults.headers.common['Content-Type'] = 'application/json;charset=utf-8;' ;
$http.defaults.headers.common['Auth-Token'] = 'X-Requested-With';
$http.defaults.headers.common['Authorization'] = $('#Authorization').val();
Access-Control-* headers are response headers. They come from the server in response to a request. You do not apply them to your request headers.
If your jQuery request works correctly without adding any additional headers, then your AngularJS request should work the same.
The equivalent jQuery request in AngularJS (including removing the Authorization and Auth-Token headers you've set via defaults) is
$http.post(getAccessTokenUrl, clientdata, {
headers: {
Authorization: undefined,
'Auth-Token': undefined
}
}).then(response => {
console.log(response.data)
})
or the long version
$http({
method: 'POST',
url: getAccessTokenUrl,
data: clientdata,
headers: {
Authorization: undefined,
'Auth-Token': undefined
}
}).then(...)
AngularJS by default...
POSTS requests as application/json content-type
Serializes the data property to JSON
Expects a JSON response
Resolves the $http promise with a response object with the response body parsed as JSON into the data property
Remove the following setting
$http.defaults.headers.common['Auth-Token'] = 'X-Requested-With';
$http.defaults.headers.common['Authorization'] = $('#Authorization').val();
Add Authorization header dynamically from Interceptor
request: function(config) {
if (angular.isUndefined(config.skipInterceptor) || !config.skipInterceptor) {
// add Authorization token
}
return config;
}
Http call like this
$http.post('your url', {
skipInterceptor: true
})

How to handle CORS requests in AngularJS

I'm facing problem with CORS requests in AngularJS while calling web services but the same service able to call by using jQuery.
Note: From server side we are receiving header "Access-Control-Allow-Origin:*" and these services are running fine in jQuery application.
Here I'm posting my AngularJS code as well as jQuery code.
AngularJS:
$http({
method: 'POST',
url: $rootScope.host + "UserLogin",
//headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: {
"uname": $scope.uname,
"password": $scope.password
},
}).then(function (success) {
$scope.loginDetails = success;
console.log($scope.loginDetails);
}),function (error){
console.log(error);
});
If I pass the header like headers: { 'Content-Type': 'application/x-www-form-urlencoded' } able to ping the service but my request is not going in JSON format.
If I change the header to 'Content-Type': 'application/json', getting
XMLHttpRequest cannot load https://XXXX.XXXX.in/XXXXAPI/UserLogin.
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://170.11.0.61' is therefore not allowed access.
I don't know what is the reason for this error.
$.ajax({
url: BASE_URL + "UserLogin",
type: "POST",
xhrFields: {withCredentials: true},
data: {
"uname": uname,
"password": password
},
cache: false,
success: function (result, textStatus, request) {
console.log(result);
},
error: function (e) {
console.log("Error in login service call:"+JSON.stringify(e));
}
});
This jQuery is sending my request in the json format.
Try to pass headers like
headers: { 'Content-Type': 'application/json' }

AngularJS HTTP GET request returning cached data

In my AngularJS app I am sending HTTP GET request as below.
MyService.HttpReq("testUrl", "GET", null);
HttpReq Method is defined in a service and implemented as below:
this.HttpReq = function(URL, method, payload)
{
$http({
url: URL,
method: method,
cache: false,
data: postData,
headers: {
'Content-Type': 'application/json',
}
}).success(function(response)
{
console.log("Success: "+JSON.stringify(response));
}).error(function(data, status)
{
console.error("Error");
});
}
First of all is this the right way of sending HTTP request in AngularJS?
The problem that I am facing is, some times I get cached data as response and HTTP request is not hitting the server. what can be the issue?
UPDATE
As per the comment and answer I have updated my HTTP request code as below, but still getting same issue.
this.HttpReq = function(URL, method, payload)
{
$http({
url: URL,
method: method,
cache: false,
data: payload,
headers: {
'Content-Type': 'application/json',
'Cache-Control' : 'no-cache'
}
}).
then(
function(response)
{
var data = response.data;
console.log("Success: "+JSON.stringify(data));
},
function(response)
{
var data = response.data || "Request failed";
var status = response.status;
console.error("Error: "+JSON.stringify(data));
}
);
}
IE Browsers will catch ajax get requests even if we add cache control headers to the response. Only way i found to solve the issue is to add some random parameter to the request. Please make sure the api have no problem even if you send extra parameters
MyService.HttpReq("testUrl?ts=" + Date.now(), "GET", null);
Just add cache: false attribute to config object.
https://docs.angularjs.org/api/ng/service/$http#caching
Also you can add header: 'Cache-Control' : 'no-cache'

Resources