I'm trying to make a get request with some params to a Spring get method. I'm using angular to make a call and this is my example
var apiUrl = 'api/trupci-filter';
var req = {
method: 'GET',
url: apiUrl,
headers: {
'Content-Type': "application/x-www-form-urlencoded" or "application/json"
},
data: {
klasa: "1",
promjer:"1",
duzina: "1"
}
}
console.log(req)
return $http(req)
And this is my get method in Spring:
#GetMapping("/trupci-filter")
#Timed
public ResponseEntity<List<Trupci>> getTrupciWithFilter(
#RequestParam(value = "klasa", required = false) String klasa,
#RequestParam(value = "promjer", required = false) String promjer,
#RequestParam(value = "duzina", required = false) String duzina )
The call is successful but the params are always null. I can't find any solution to this simple thing and I'm losing my mind.
Can anybody help me?
HTTP GET request can't have data element, its for request body like for HTTP POST, PUT etc. Please use params for query string parameters.
var req = {
method: 'GET',
url: apiUrl,
params: {
klasa: "1",
promjer:"1",
duzina: "1"
}
}
Related
Spring boot is not getting the params in the request body.
The controller is defined like:
#PostMapping("/login")
public #ResponseBody User login(#RequestBody String username, #RequestBody String password) {
return userService.login(username,password);
}
And the fetch in React
const LogFunc = async () => {
let url = new URL("http://localhost:8080/user/login");
let params = {
username: username,
password: password
}
console.log(JSON.stringify(params));
return fetch(url, {
method: 'POST',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify(params)
When i console.log it, it prints it like
{"username":"allanosi","password":"cap"}
which is correct but when Spring receive it, it prints:
Required request body is missing: public com.formacion.back.entities.User com.formacion.back.controllers.UserController.login(java.lang.String,java.lang.String)]
On the network part it says that it's a bad Request but I have no idea why it is.
Thanks in advance.
Can you try this? Just replace the annotation with this.
#RequestMapping(
value = "/login",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
Another guess, spring boot is waiting string not object that's why you might getting request body is missing error. You can try this:
public #ResponseBody User login(#RequestBody Map<String, String> userData) {
// your code
}
Maybe you can try this:
const fdata = new FormData();
fdata.append('username', 'diego');
fdata.append('password', '1242342');
fetch(url, {
method: 'POST',
headers: ...,
body: fdata,
});
I had the same problemas as you and this approach has fixed my problem.
I am trying to use angularjs POST (or even GET) to a servlet with the following:
var json = { hello: "world" }
var deffered = $q.defer();
$http({
method: "POST",
url: url,
headers: { "Content-Type" : "application/json" },
request: JSON.stringify(json)
}).then(data) {
if(data.data) {
deferred.resolve({
response : data
});
)
})
return deffered.promise;
within the servlet, simple:
String val = request.getParameter("request")
it never seems to see it
I have tried:
data: JSON.stringify({ request: json })
data: { request: json }
"request" : JSON.stringify(json)
etc
if I comment out the getParameter and just return a generic value using Gson
JsonObject json = new JsonObject();
json.addProperty("This", "works");
response.getWriter().print(new Gson().toJson(json));
that comes back fine so is there something within the angular POST I am doing wrong here? I have also tried using "GET" instead but same result.
EDIT: I would like to understand POST method and the "proper" way to get the data from the json object if getParameter is wrong please~
getParameter() returns http request parameters, you should add this params by using :
params: JSON.stringify(json)
Not with
request: JSON.stringify(json)
Take a look in params in get and params in post.
I am facing a specific issue with making a post call using Angular js, the below code fails with error:
Response for preflight has invalid HTTP status code 404
How ever if I make the same call by passing parameters in plain text format, by appending values directly in URL it works. Any help here is appreciated.
eg: https://sample.com/services/srest/restserver/v1.0/authenticate/login?username=rakesh&password=somepassword
angular.module("sampleApp2",[])
.service("apiCalls",function($http) {
var result;
var postdata = {username: "rakesh", Password: "somepassword"} ;
this.cobLogin = function(callback,errcallback) {
result = $http({
method:'POST',
data:postdata,
url:'https://sample.com/services/srest/restserver/v1.0/authenticate/login'
}).then(callback, errcallback);
}
return result;
});
Provide headers
angular.module("sampleApp2",[])
.service("apiCalls",function($http) {
var result;
var postdata = {username: "rakesh", Password: "somepassword"} ;
this.cobLogin = function(callback,errcallback) {
result = $http({
method:'POST',
url:'https://sample.com/services/srest/restserver/v1.0/authenticate/login',
data:postdata,
headers: { 'Content-Type':'application/json'}
}).then(callback, errcallback);
}
return result;
});
It sounds like you are using the wrong content type. The default is Content-type: application/x-www-form-urlencoded. You want Content-type: application/json. You can set this in the headers option. Check the $http docs
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': 'application/json'
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
I'm trying to send HTTP request using the following code:
var editCompanyUrl = 'http://X.X.X.X:YYYY/editCompany';
var userId = localStorage.getItem("UserId");
var token = localStorage.getItem("Token");
var companyId = localStorage.getItem("companyId");
return $http({
method: 'POST',
url: editCompanyUrl,
params: {
token: token,
userId: userId,
companyId: companyId,
companyName: $scope.companyName,
},
timeout: 500
}).then(function (data) {
console.log(data);
//Store Company ID which is used for saving purposes
//localStorage.setItem("companyId", data.data.Company.id);
return data.data.Company;
}, function (data) {
console.log(data);
})
and handler of the request on the server side accepts requests with Content-Type: multipart/form-data. How can I add this content type to the request? I've tried many advices and tips from tutorials but no success. Could you please help me? In addition to it - what should I do when I will add a file with an image to this request? Can I just add it as additional parameter of the request?
Thank you very much!
Angular POST must be like below code.
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
it should have data:{ }
so try to put your params: inside the data and it should work.
Should we send json array or normal array as querystring in senchatouch2
in any case you can only send String in URL so if you have JSON then use Ext.JSON.encode to make it string and if you have JS Array use toString or join method to flatten the array before appending it to URL.
Since you said querystring so I suppose you and not doing POST request.
[EDIT]
Looking at your comment it seems you want to send some data to service for creation but in that case you should not send data as querystring, you should send it in message body. Following is example to send JSON data to your service:
var obj = new Object();
obj.loginEntry = new Object();
obj.loginEntry.userid = username;
obj.loginEntry.password = password;
var data = Ext.JSON.encode(obj);
Ext.Ajax.request({
url : 'http://myserver:port/service/entity',
method : "POST",
headers: {
/* Important because default is
* Content-Type:application/x-www-form-urlencoded; charset=UTF-8
* which is not supported by service
*/
'Content-Type': 'application/json'
},
params : data,
success : function(response) {
},
failure : function(response) {
}
}
);
[/EDIT]
While we use POST method to send parameters in Sencha Touch2 use jsonData in Ajax Request like,
Ext.Ajax.request({
url:'',
method:'POST',
disableCaching:false,
headers: {
'Accept':'application/json',
'Content-Type':'application/json'
},
jsonData: {
FirstName:fname //{"FirstName":["Sam","paul"]}
},
success: function(response)
{
console.log(response.responseText);
},
failure: function(response)
{
console.log(response.responseText);
},
});