【问题标题】:Error transmitting data using RESTful HTTP使用 RESTful HTTP 传输数据时出错
【发布时间】:2021-10-29 09:41:35
【问题描述】:

我需要将数据从 Java Servlet 后端传输到前端。数据以 JSON 格式传输,这就是我为实现它而编写的 servlet:

@WebServlet("/add")
public class AddElementServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("application/json");
    PrintWriter printWriter = resp.getWriter();
    printWriter.write("{\"id\":1,\"content\":\"Hello, World!\"}");
    printWriter.close();
}
}

该地址的网页显示的是 JSON 字符串。同时,前端没有得到传输的数据。我的猜测是使用 RequestDispatcher,但我看不到 .forward().redirect() 方法在这里有用。 那是我用来接收数据的前端版本。 第一个:

$(document).ready(function() {
$.ajax({
    url: 'http://localhost:8081/add'
}).then(function(data) {
    alert('Data: '+ data + ' ' + data.id + ' ' + data.content);
    $('.greeting-id').append(data.id);
    $('.greeting-content').append(data.content);
});
});

第二个:

fetch('http://localhost:8081/add')
.then(function(response) {
    return response.json()
}).then(function(json) {
console.log('parsed json', json)
}).catch(function(ex) {
console.log('parsing failed', ex)
})

我的错误在哪里,我该如何解决?

【问题讨论】:

  • 访问前端时,浏览器控制台有什么消息吗?
  • Postman 有什么回应吗?
  • @PeterMmm,在第二种情况下,它只显示“解析的 json”。
  • @JanezKuhar,是的,我得到的回复与我预期的完全一样。
  • 我相信 Postman 可以选择生成与您的请求等效的 JavaScript。见:Generating client code

标签: java rest servlets


【解决方案1】:

出现了CORS策略的问题,我尝试通过将mode: 'no-cors'添加到fetch()来解决。但这由于某种原因不允许传输数据 - 这样只有浏览器的特殊扩展可能会有所帮助。在浏览器开发者页面的扩展市场中搜索。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-14
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多