I've been working on a react app. In this app, I will be sending the input from the user to the Java servlet on the tomcat server to sort it. After sorting, I'm trying to display it on a label in my react app. I've successfully sent it to the java servlet using fetch method() and sorted it.
This is how my fetch() method looks like:
const [text, setText] = useState("");
async function onSubmit() {
var newText = { text: text}; //object
await fetch(`http://localhost:8080/backend/link`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : true,
"status" : 200
},
body: JSON.stringify(newText),
mode: 'no-cors',
})
.then((response) => {
console.log("response");
console.log(response.body); //displays null
})
.then((data) => {
console.log(data);
console.log("Success");
});
}
My Java servlet looks like this:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
System.out.println("invoked");
String jsonBody = new BufferedReader(new InputStreamReader(request.getInputStream())).lines().collect(
Collectors.joining("\n"));
System.out.println(jsonBody);
if (jsonBody == null || jsonBody.trim().length() == 0) {
return;
}
JSONObject jObj;
try {
jObj = new JSONObject(jsonBody);
String lines[] = ((String) jObj.get("text")).split(","); //The words in the input are separated by comma
Arrays.sort(lines);
for (String a : lines)
System.out.println(a);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
} catch (JSONException e) {
System.out.print("Exception");
}
}
whatever I send in the response object (Using Printwriter), the fetched response's body is null. How can I send the array so that I can get it in the response object of the fetch and then display it in a label?
Please leave your suggestions
CodePudding user response:
I do not see where you write the body in the servlet response.
Perhaps you need something like this:
final PrintWriter writer = response.getWriter();
for (String a : lines)
writer.println(a);
Note: your client is expecting a JSON object back, so you probably want to write your jObj to the output and not lines of text.
CodePudding user response:
From your code it's not clear how did you use PrintWriter. You can try something like below and then check the response:
String message = new ArrayList<String>();
PrintWriter writer = response.getWriter();
JSONObject obj = new JSONObject();
obj.put("message",message);
response.setStatus(200);
writer.append(obj.toString());
writer.close();
Put a string message on JSON object to check whether nothing is being passed or only response is not being passed. Call "response.message" to fetch the message on client side.
CodePudding user response:
const [text, setText] = useState(""); async function onSubmit() {
var newText = { text: text}; //Create a json object here and pass it to body
await fetch(`http://localhost:8080/backend/link`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : true, "status" : 200 }, body: newText, //do not need to use any json stringfy method mode: 'no-cors', }) .then((response) => { console.log("response"); console.log(response.body); //displays null }) .then((data) => { console.log(data); console.log("Success"); }); }

