简体   繁体   English

如何从 java servlet 发送一个数组作为 JSON 以使用 fetch() 响应前端?

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

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.在这个应用程序中,我会将用户的输入发送到 tomcat 服务器上的 Java servlet 以对其进行排序。 After sorting, I'm trying to display it on a label in my react app.排序后,我试图在我的反应应用程序的 label 上显示它。 I've successfully sent it to the java servlet using fetch method() and sorted it.我已经使用 fetch method() 成功地将它发送到 java servlet 并对其进行了排序。

This is how my fetch() method looks like:这就是我的 fetch() 方法的样子:

 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:我的 Java servlet 如下所示:

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.无论我在响应 object(使用打印机)中发送什么,获取的响应正文都是 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?如何发送数组以便我可以在获取的响应 object 中获取它,然后在 label 中显示它?

Please leave your suggestions请留下您的建议

I do not see where you write the body in the servlet response.我看不到您在 servlet 响应中写正文的位置。

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.注意:您的客户期望返回 JSON object,因此您可能希望将您的 jObj 写入 output 而不是文本行。

Use google chrome debug to view response headers of your network request.使用 google chrome debug 查看网络请求的响应标头 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.我的猜测是您的客户端代码很好,服务器没有在正文中发送任何内容。

在此处输入图像描述

From your code it's not clear how did you use PrintWriter.从您的代码中不清楚您是如何使用 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.在 JSON object 上放置一条字符串消息,以检查是否没有传递任何内容或只有响应没有传递。 Call " response.message " to fetch the message on client side.调用“ response.message ”在客户端获取消息。

I do not see where you write the body in the servlet response.我看不到您在 servlet 响应中写正文的位置。

Perhaps you need something like this:也许你需要这样的东西:

final PrintWriter writer = response.getWriter();
for (String a : lines)
           writer.println(a);

Use google chrome debug to view response headers of your network request.使用 google chrome debug 查看网络请求的响应标头 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.我的猜测是您的客户端代码很好,服务器没有在正文中发送任何内容。

在此处输入图像描述

const [text, setText] = useState(""); const [文本,setText] = useState(""); async function onSubmit() {异步 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"); }); "Access-Control-Allow-Credentials": true, "status": 200 }, body: newText, //不需要使用任何 json stringfy 方法 mode: 'no-cors', }).then((response) => { console.log("response"); console.log(response.body); //显示 null }).then((data) => { console.log(data); console.log("Success" ); }); } }

It was because I used "no-cors" mode in the client side which means that JavaScript cannot access the properties of the resulting response.这是因为我在客户端使用了“no-cors”模式,这意味着 JavaScript 无法访问结果响应的属性。 Here's a detailed explanation about it: https://stackoverflow.com/a/43319482/13893049 .这是关于它的详细说明: 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.由于 json 格式不是允许的类型之一,因此我在客户端和服务器端进行了多项修改,包括将内容类型从 application/json 更改为 text/plain。

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.如果您有任何疑问,请在评论中告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM