How to send an array as JSON from java servlet to react frontend using fetch()?

Solution 1:

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.

Use google chrome debug to view response headers of your network request. There you can see the body of the response. My guess is that your client-side code is fine and the server is not sending any content in the body.

enter image description here

Solution 2:

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.

Solution 3:

 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");
        });
    }