我不使用fetchapi从javaservlet获取响应数据

tvmytwxo  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(201)

我想使用fetchapi发布数据并以json格式获取响应。前端:javascript,后端javaservlet,postgresql。我的问题是我没有从servlet得到响应。我在浏览器控制台中没有看到json格式的数据。
javascript代码

let button = document.getElementById("inputSubmit");

button.addEventListener("click", postData);

function postData(){

fetch("http://localhost:8080/StudentRegisterApplication/register", {
    method : "POST",
    headers : {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    body : JSON.stringify({
        username : "Jack"
    })
}).then(function(response) {
 return response.json();
}).then(function(data) {
    console.log(data);
});

}
java servlet代码

public static void getAllStudents(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    ObjectMapper om = new ObjectMapper();
    resp.setContentType("application/json");        

    List<Student> students = studentService.getAllStudents();

    PrintWriter pw = resp.getWriter();

    String json = om.writeValueAsString(students);
    System.out.println(json);

    pw.write(json);

}

//当我打印字符串“json”时,我在java控制台中以json格式打印所有学生,但是pw.write(json)是fetchapi的响应???我在浏览器中看不到这些数据??谢谢你的帮助。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题