React fetch to Java backend returning null - java

I currently have a react button that should be sending data from the state to a servlet via post. The server is getting hit from the fetch method but the data appears to be null.
fetch(
"http://localhost:8080/askQuestion",
{
method: "post",
body: {
question: this.state.value
},
headers: {
"Content-Type": "application/text"
}
}
).then(console.log(this.state.value));
The value in my request object for both body and question are null
request.getParameter("question");
request.getParameter("body");

You can use getInputStream() or getReader() to read body attributes of the requests.
Here is an easy (not conventional) way to get your work done:
Write your body attributes in headers:
headers: {
"Content-Type": "application/text",
'question': this.state.value
}
In backend, use request.getHeader("question") to get the value.

You can try sending json data as the body of your post request
fetch('http://localhost:8080/askQuestion', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({ question: this.state.value })
}).then(res => res.json())
.then(res => console.log(res));

Related

Error javax.json.stream.JsonParsingException: when making an AJAX API call

I have developed a web based program using java jersey in my back end and jsp in my front end. When I make a post API call using Ajax my back end gets the following exception.
javax.json.stream.JsonParsingException: Unexpected char 117 at (line
no=1, column no=1, offset=0)
I guess it's something wrong with the data which I'm passing through the Ajax API call.
Here is my ajax API call:
var obj = JSON.parse('{ "userName":"John", "password":"hgvv", "img":"New York","fname":"kjbjk","lname":"bkbkkj","tp":"buhb","address":"jhbjhb","type":"user"}');
$.ajax({
type: "POST",
url: $url,
contentType: "application/json",
data: obj,
dataType: 'json',
success: function () {
alert("successed");
}
});
This is my back end implemented code:
#Path("testing")
public class test {
UserRepository userRepo=new UserRepository();
#Path("users")
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public UserModel CreateUser(UserModel a) {
userRepo.createUser(a);
return a;
}
}
You should send the data as a JSON String, not a JSON Object. Avoid the JSON.parse from your code.
var data = '{ "userName":"John", "password":"hgvv", "img":"New York","fname":"kjbjk","lname":"bkbkkj","tp":"buhb","address":"jhbjhb","type":"user"}';
Alternatively, I would construct the JS Object, and apply JSON.stringify on it. This way, the code is more readable:
var data = {
userName: "John",
password: "hgvv",
img: "New York",
fname: "kjbjk",
lname: "bkbkkj",
tp: "buhb",
address: "jhbjhb",
type: "user"
};
$.ajax({
type: "POST",
url: $url,
contentType: "application/json",
data: JSON.stringify(data), // added JSON.stringify here
dataType: 'json',
success: function () {
alert("successed");
}
});

Backend return html but frontend does not redirect

I hit an api endpoint and I checked the network call responses with an html response with status code of 302. However, I don't see the redirect happening on the UI. The redirect is to another application (a different url)
export function callThis(payload) {
const url = "some-path";
const headers = getHeaders();
return fetch(url, { method: 'POST', headers: headers, body:
JSON.stringify(payload) })
.then((response) => response.json());
}
Is there something I'm missing?
try to help but with this snippet, you didn't show your "redirect part" if you are using reactjs you should have a look at DOM Router and using Redirect or push history.
You should use redirect: 'follow' in the request options.
export function callThis(payload) {
const url = "some-path";
const headers = getHeaders();
return fetch(url, { method: 'POST', redirect: 'follow', headers: headers, body:
JSON.stringify(payload) })
}
If you want to know the redirect url and do manual operation, you have to use redirect: 'manual'.
export function callThis(payload) {
const url = "some-path";
const headers = getHeaders();
return fetch(url, { method: 'POST', redirect: 'manual', headers: headers, body:
JSON.stringify(payload) })
.then((response) => {
const redirectUrl = response.url // new redirect url
})
}
Hope this helps!

Spring Rest Service throwing HTTP Status 415

Hi I am trying to call a Spring rest service from angular but I am getting the below error. Even from The Postman I am getting the same error.It looks like something is wrong with the rest service, which is not accepting the json request data
HTTP Status 415 : The server refused this request because the request entity is in a format not supported by the requested resource for the requested method. Thanking everyone in advance.
Below is the code
**Angular Code**
var req = {
method: 'POST',
url: 'http://localhost:9050/FastTrackALM/retrieveData/getEpicData',
headers: {
'Content-Type': 'application/json'
},
data: {'epicId': '1' }
}
$http(req).then(function(response){
console.log(response);
}, function(response){
console.log(response);
});
**REST SERVICE**
#RequestMapping(method=RequestMethod.POST,
value="/getEpicData",
consumes={"application/json"},
produces={"application/json"})
#ResponseBody
#ResponseStatus(code = HttpStatus.OK)
public DataActionObject insertStudentDetails(#RequestBody epicForm1 student){
DataActionObject dataActionObject = new DataActionObject();
dataActionObject=epicBusinessBean.getEpicData(student.getEpicId(), dataActionObject);
return dataActionObject;
}
DataActionObject is my custom class that holds the json date to be returned to client along with message an code

Failed to load resource: the server responded with a status of 415 (Unsupported Media Type) in Java RESTful web service call

I have the following javascript in my test html page to send ajax requests to a java restful web service I built with netbeans (mostly auto generated by using 'Restful web services from database' function).
Here is the ajax query from my test html page:
$(function(){
$('.message-button').on('click', function(e){
var resultDiv = $("#resultDivContainer");
$.ajax({
headers: { 'Accept': 'application/json',
'Content-Type': 'application/json'
},
'type': 'POST',
'url': 'http://localhost:8080/xxxAPI/api/activity',
'data': { "baseItemId": "2" },
'dataType':'json',
'success': function(data) {
var xmlstr = data.xml ? data.xml : (new XMLSerializer()).serializeToString(data);
$("#resultDivContainer").text(xmlstr);
},
'error': function(jqXHR, textStatus, errorThrown) {
alert(' Error in processing! '+textStatus + 'error: ' + errorThrown);
}
});
})
});
Also here is the part of my java code that accepts post requests:
#POST
#Override
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void create(XxxxxActivity entity) {
super.create(entity);
}
When I request from the test page (for this version of the test page), I get this error:
Failed to load resource: the server responded with a status of 415
(Unsupported Media Type)
or this error:
POST http://localhost:8080/xxxAPI/api/activity 415 (Unsupported
Media Type)
So far I have tried making various changes to the ajax request as advised on similar questions on stackoverflow, including changing type to jsonp, putting json data in double quotes, adding headers and changing data type to xml. None of them have worked.
Also since I manage to get a response from the server at times, I wonder if the issue is with xml parsing in the java code. I believe a potential fix would be to add the jackson jar files, but I have no idea how to add them on netbeans as there is no lib folder in WEB_INF.
I would also like to know if there is any issue with the jquery ajax request. This issue has been bugging me for days.
PS: Also note that GET requests from the browser work fine. I have not used maven in this project.
Replace
'data': { "baseItemId": "2" },
with
'data': JSON.stringify({ "baseItemId": "2" }),
Object JSON is available here.
EDIT
add attribute contentType: 'application/json; charset=UTF-8'
remove attribute headers from ajax call.
Frondend
$.ajax({
contentType: "application/json; charset=utf-8",
url: '/GetList',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ 'Name': 'mehmet erdoğdu'}),
beforeSend: function () {
}, success: function (data) {
}, complete: function () {
}, error: function (data) {
}
});
Backend
[HttpPost]
public JsonResult GetList([FromBody] NameRequest req)
{
var selectListItems = new List<SelectListItem>
{
new SelectListItem
{
Value = "",
Text = "Select Name"
}
};
//
return Json(selectListItems, new JsonSerializerSettings());
}

Spring MVC: Receive XML data and Send String message back

I am trying to collect all the form data and send it as a XML to Controller. This XML will further be sent to back end which will take care of it.
There is no need to marshal this XML into an Object.After receiving this XML I just need to send a String success message back.
It is half working. I am able to receive XML message from UI page and able to print it on console. But when I just send success message back UI ajax call receives No conversion from text to application/xml
#RequestMapping(value="/save",method=RequestMethod.POST,consumes={"application/json", "application/xml", "text/xml","text/plain"})
#ResponseBody public String handleSave(#RequestBody String formData)
{
System.out.println("comes here");
System.out.println(formData);
return "Success";
}
$('form').submit(function () {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
processData: false,
data: collectFormData1(),
headers: {
"Content-Type":"application/xml"
},
dataType: 'application/xml',
success: function (data) {
alert('Success:'+data)
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('jqXHR:'+jqXHR+'\n'+'textStatus:'+'\n'+textStatus+'errorThrown::'+errorThrown);
}
});
return false;
});
Try to remove dataType: 'application/xml' from jquery code.
As mentioned in documentation: DataType: The type of data that you're expecting back from the server.
(http://api.jquery.com/jQuery.ajax/)

Categories