Issue
I need to transmit data from Java Servlet backend to frontend. The data is transmitted in JSON and that's the servlet I've written to implement it:
@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();
}
}
The web-page on this address shows the string of JSON. At the same time, the front doesn't get the data transmitted. My guess is to use RequestDispatcher, but I see neither .forward()
nor .redirect()
method useful here.
That's the versions of the frontend that I used to receive data.
1st:
$(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);
});
});
2nd:
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)
})
Where is my mistake and how can I solve it?
Solution
The problem of CORS policy appeared, and I tried to solve it by adding mode: 'no-cors'
to fetch()
. But that didn't allow to transmit data for some reason - this way only a special extension to a browser may help. Search for it in extension markets of your browser developers' page.
Answered By - coder-coder