How to send a rest PUT request in angular passing body - javascript

I need to send a rest request to a web server, I am using this code :
var getData = function(...) {
return $http({
method: "PUT",
url: getStatistics,
headers: {
'loginId': ...,
'token': ...,
'Content-Type': 'application/x-www-form-urlencoded',
},
data: {"...":"...","...":"...","...":"...","...":"...",
"...":"....","....":"...",
"datefrom":"2017-01-01","dateto":"2017-10-20"}
}).then(function(result){
var dataString = JSON.stringify(result.data);
alert(result.data);
return result.data;
});
};
The problem is that I am receiving error 400 bad request, What should I do?
The request works on Postman With this structure
https://i.stack.imgur.com/BBrwF.jpg
https://i.stack.imgur.com/NbQuO.jpg
Should it be a problem of how Am I passing the data object ?
That's how I implemented the $httpParamSerializerJQLike, it it Correct?
app.factory('statistics', function($http,$httpParamSerializerJQLike) {
var getData = function(loginId,token,id,dataInizio,dataFine,periodo,selezione) {
// Angular $http() and then() both return promises themselves
var data = '{"datefrom":"2017-01-01","dateto":"2017-10-20"}';
alert(data);
return $http({
method: "PUT",
url: getStatistics,
headers: {
'loginId': loginId,
'token': token,
'Content-Type': 'application/x-www-form-urlencoded',
},
data: { 'data': $httpParamSerializerJQLike(data)}
}).then(function(result){
var dataString = JSON.stringify(result.data);
alert(result.data);
return result.data;
});
};
return { getData: getData };
});

you're sending an x-www-form-urlencoded body, but it contains a single parameter named data, containing JSON.
You thus need
data: $httpParamSerializerJQLike({data: angular.toJson(data)})

Related

How do you express it using the fetch API in JavaScript?

Now, I POST image data using ajax(jquery) as follows. The image is a File object.
async function postImage({ image }) {
const result = await $.ajax({
method: 'POST',
url: '/api/images',
dataType: 'json',
data: image,
processData: false,
async: true,
headers: {
'Content-Type': 'application/octet-stream',
},
});
return result;
}
The result that return object is {id: imageID}.
How can I express this using the Fetch API? I couldn't get the result even if I did the following.
const result = await fetch('/api/images', {
method: 'POST',
body: image,
headers: {
'Content-Type': 'application/octet-stream',
},
});
return result;
fetch() returns a promise to a Response object, and that has a json() method which returns another promise to the parsed response JSON.
const response = await fetch('/api/images', {
method: 'POST',
body: image,
headers: {
'Content-Type': 'application/octet-stream',
},
});
const result = await response.json();

Javascript Fetch Body JSON List

I am trying to make a post request and getting this exception:
"unsupported BodyInit type"
I think the issue is with the body of the request. phoneNumbers takes on the form phoneNumbers = ["1234567890", "1234567891"] (i.e. a list of strings). I tried to do JSON.stringify(phoneNumbers) as the body, but that seems to return "[]", even if the list is not empty.
export async function findUsersByPhoneNumbersNotFollowing(userId, phoneNumbers) {
const reqConfig = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: phoneNumbers,
};
const response = await authfetch(`${API_URL}/following/recommendations/${userId}`, reqConfig);
if (response.error) {
throw new Error(response.error);
}
return response;
}
Where am I going wrong? The API endpoint is expecting List<String> (using spring framework, and the controller method takes this param in annotated #RequestBody)
Try sending a JSON Object instead a plain array:
const reqConfig = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
paramName: phoneNumbers
}),
};
Replace paramName for the name you are expecting on your API endpoint.

$http get null when use phone browser

I use $http to make a POST request to get my imugur access token, and everything work fine on my PC browser.
But when I use my android phone(ios not sure, haven't tried it), I get an error and from the console.log I see NULL.
I have no idea how to fix this, can anyone help?
Thanks
$http({
method: 'POST',
url: "https://api.imgur.com/oauth2/token",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: { client_id: "my_cliendID", client_secret: "my_clientSecret", grant_type: "refresh_token", refresh_token: "my_refreshToken" }
}).success(function (e) {
callback(e);
}).error(function (e) {
console.log(e);
});
=========================================================.
when I use $http I get the NULL value, so I try to use $resource but still the same issue. PC work fine, but when use phone I still get an error from function (error) {alert(JSON.stringify(error))}); now I get some response instead of NULL value. (refer to image)
var token = $resource("https://api.imgur.com/oauth2/token", null, {gettoken: {method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded'}}
function getAccess(callback) {
data= { client_id: "my_cliendID",
client_secret: "my_clientSecret",
grant_type: "refresh_token",
refresh_token: "my_refreshToken"
}
var toke = token.gettoken($httpParamSerializer(data),
function (success) {
alert(JSON.stringify(success))
responseSuccess(success, null, callback)
},
function (error) {
alert(JSON.stringify(error))
responseError(error, callback)
});
};
after I tried with jquery ajax, it work on both side(PC & mobile)
Don't know why angular $http & $resource not working on mobile browser.
data= { client_id: "client_id",
client_secret: "client_secret",
grant_type: "refresh_token",
refresh_token: "refresh_token"
}
$.ajax({
type: "POST",
url: 'https://api.imgur.com/oauth2/token',
data: $httpParamSerializerJQLike(data),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success: function(res) {
callback(res);
},
error:function(res){
}
});

Unable to upload file using angular JS and Spring controller

I am not understanding url: '/api/fileupload/',
$scope.uploadFiles = function () {
var request = {
method: 'POST',
url: '/api/fileupload/',
data: formdata,
headers: {
'Content-Type': undefined
}
};
// SEND THE FILES.
$http(request)
.success(function (d) {
alert(d);
})
.error(function () {
});
}
This is the code I used a while ago to upload xlm files using angular:
this.uploadFile = function($file) {
// $http() returns a $promise that we can add handlers with .then()
return $http({
method: 'POST',
url: restUrl + "/rest/data/upload",
data: $file,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
Also make sure you are accepting MediaType.MULTIPART_FORM_DATA on your server

Get data from ajax request to Angular

I have 2 requests
$.ajax({
type: "POST",
url: "http://sandbox.gasvisor.com:9988/uaa/oauth/token",
data: "grant_type=client_credentials",
headers: { 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization':'Basic SVRXRV9XRUJfQVBQOml0d2VfY2xpZW50' },
success:function(data){
console.log(data);
getData(data.access_token);
}
})
function getData(acess_token){
$.ajax({
type: "GET",
url: "http://sandbox.gasvisor.com/api/v2/gobjects/search/withinRadius?longitude=24.711117&latitude=48.922633&radius=10",
headers: {
'Authorization':'bearer'+acess_token },
success:function(data){
console.log(data);
}
})
}
They return json from server. I need to get data from Json file to my Angular listing. Pls help me.
Here is a simple example for one of your call:
$http({
method: 'POST',
url: 'http://sandbox.gasvisor.com:9988/uaa/oauth/token',
data: 'grant_type=client_credentials',
headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization':'Basic SVRXRV9XRUJfQVBQOml0d2VfY2xpZW50' },
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.response = response;
}, function errorCallback(err) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.error = err;
});

Categories

Resources