2

I am very new to node js. I am just testing some stuff about client-server communication.

I have these codes:

server:

app.post('/zsa', (req, res) => {
    res.send("zsamo");
});
client:

fetch("http://localhost:3000/zsa", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(data),
})
  .then((data) => {
    console.log(data);
  });

With this code i get a response object:

enter image description here

I want to log to the console what was in the response data: "zsamo"

4
  • 1
    The fetch() returns a Response object. You need to transform the body into JSON data by adding a then after fetch: fetch( ... ).then( res => res.json() ).then( data => ... Commented Mar 23, 2023 at 17:56
  • Beware that zsamo is not JSON
    – Wyck
    Commented Mar 23, 2023 at 17:58
  • 1
    @jabaa The quotes are not being transmitted in the original code (res.send("zsamo")). Beware that JSON.parse("zsamo") in a modern browser will still produce SyntaxError: Unexpected token 'z', "zsamo" is not valid JSON But JSON.parse('"zsamo"') will result in a string with the content: zsamo. See this answer
    – Wyck
    Commented Mar 24, 2023 at 2:18
  • @Wyck Yes, you are right. zsamo is not JSON.
    – jabaa
    Commented Mar 24, 2023 at 2:22

2 Answers 2

3

fetch returns a Response. If you want JSON from the body of your response then you can do this:

fetch(url)
  .then(response => response.json())
  .then(data => console.log(data));

See also Using the Fetch API

4
  • 1
    Technically, it returns a Promise that resolves to a Response object.
    – Wyck
    Commented Mar 23, 2023 at 17:59
  • And how can i just display "zsamo", what was in the response data?
    – Barta
    Commented Mar 23, 2023 at 18:10
  • 1
    @Barta you can use response.text() instead of response.json() and don't send your response from the server with the Content-Type application/json but instead use text/plain
    – Wyck
    Commented Mar 24, 2023 at 2:11
  • ...or you could have transmitted your response as a quoted string, which is valid JSON: res.send('"zsamo"')
    – Wyck
    Commented Mar 24, 2023 at 2:19
0

At client side, in console.log instead of data, write data.body

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.