0

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?

coder-coder
  • 323
  • 4
  • 13
  • When you access the frontend, any message in the browser console ? – PeterMmm Aug 30 '21 at 17:30
  • Do you get any response with Postman? – Janez Kuhar Aug 30 '21 at 18:29
  • @PeterMmm, in the 2nd case it shows only "parsed json". – coder-coder Aug 30 '21 at 20:07
  • @JanezKuhar, yes, I get exactly the same response that I expect. – coder-coder Aug 30 '21 at 20:08
  • I believe Postman has the option to generate JavaScript equivalent of your request. See: [Generating client code](https://learning.postman.com/docs/sending-requests/generate-code-snippets/) – Janez Kuhar Aug 30 '21 at 20:13
  • I generated it and tried, but there is still an empty line in the console. I also tried different browsers, but the data still doesn't appear. – coder-coder Aug 30 '21 at 20:38
  • Does this answer your question? [Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?](https://stackoverflow.com/questions/20035101/why-does-my-javascript-code-receive-a-no-access-control-allow-origin-header-i) – Janez Kuhar Aug 30 '21 at 21:28
  • @JanezKuhar, no, they look similar, but are not about the same thing. – coder-coder Aug 31 '21 at 11:40

1 Answers1

0

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.

coder-coder
  • 323
  • 4
  • 13