使用 RESTful HTTP 传输数据时出错
Error transmitting data using RESTful HTTP
我需要将数据从 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)
})
我的错误在哪里,我该如何解决?
出现了CORS策略的问题,我尝试通过在fetch()
中添加mode: 'no-cors'
来解决。但由于某种原因不允许传输数据——这样只有对浏览器的特殊扩展才有帮助。在浏览器开发者页面的扩展市场中搜索它。
我需要将数据从 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)
})
我的错误在哪里,我该如何解决?
出现了CORS策略的问题,我尝试通过在fetch()
中添加mode: 'no-cors'
来解决。但由于某种原因不允许传输数据——这样只有对浏览器的特殊扩展才有帮助。在浏览器开发者页面的扩展市场中搜索它。