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