Issue
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
Solution
It was because I used "no-cors" mode in the client side which means that JavaScript cannot access the properties of the resulting response. Here's a detailed explanation about it: https://stackoverflow.com/a/43319482/13893049 . I've done several modifications on the client side as well as the server side including changing the content type from application/json to text/plain since json format is not among one of the allowed types.
The only allowed values for the Content-Type header are:
application/x-www-form-urlencoded
multipart/form-data
text/plain
Now my client side code looks like this:
var newText = { text: text, commands: new_list.join(), reg: reg };
await fetch(`http://localhost:8080/backend/link`, {
method: "POST",
headers: {
"Content-Type": "text/plain",
"Origin" : "http://localhost:3000/",
},
body: JSON.stringify(newText),
})
.then((response) => response.text())
.then((data) => {
//console.log("Success");
//console.log(typeof data);
setRes(regex(data));
});
}
(I've added few variables for my requirement)
From the server side I'm sending back an array in the form of string. I'm answering my own question since someone in the future might find in helpful. Do let me know in the comments if you got any doubts.
Answered By - Sharon Shelton
Answer Checked By - Robin (JavaFixing Admin)