Send from JavaScript fetch and reply from Java Spring Boot

JavaScript (發送方)

const sendFromJavascript = () => {
  let sendData = "this is data";

  fetch("/myTest",{
     method:"POST",
     headers:{"Content-Type":"application/json"},
     body: JSON.stringify({"some_data": sendData})
  }).then((response) => {
       response.json().then(data => {
           console.log(data);
       });
   }).catch(err => {
      console.log(err);
   });
}

Java Spring Boot (接收方)

@RequestMapping(value = "/myTest", method = "RequestMethod.POST")
@ResponseBody
public myData myTest(@RequestBody String received_json_data){
    JSONObject jsonObject = new JSONObject();

    System.out.println("Retriece data -> " + jsonObject.getString("some_data"));

   //do something

   myData reply_data = new myData();
   reply_data.setField1("data_1");
   reply_data.setField2("data_2");

   return reply_data;
   
}

class myData{
   String field1;
   String field2;

    public String getField1(){
        return field1;
    }

    public void setField1(String field1){
       this.field1 = field1;
    }

    public String getField2(){
         return field2;
    }

    public void setField2(String field2){
        this.field2 = field2;
    }
}

開始在上面輸入您的搜索詞,然後按回車進行搜索。按ESC取消。

返回頂部