skip to Main Content

I’m getting a response from a server, which returns a response which has a message.
But I can’t figure out how to convert the message to json

I tried just converting it like this

.then((response) => {
   return response.message.json();
})

But that didn’t work

This is my current code

fetch(`http://127.0.0.1:80/grab`, {
        method: "post",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },

        body: JSON.stringify({
          token: token,
          key: "grab_links",
          index: 10
        }),
      })
        .then((response) => {
          return response.json();
        })
        .then((data) => {
          console.log(data)
          const linksHTML = data
        });

So how would I do this?

2

Answers


  1. As stated in the documentation, you can set the whole response to json and then call the message part. ( more info on https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch )

    fetch("http://example.com/movies.json")
      .then((response) => response.json())
      .then((data) => console.log(data));
    

    Or in your case:

    fetch("http://example.com/movies.json")
      .then((response) => response.json())
      .then((data) => {
         return data;
      });
    

    Another way of converting JSON to JavaScript is JSON.parse (more info on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse):

    const json = '{"result":true, "count":42}';
    const obj = JSON.parse(json);
    
    console.log(obj.count);
    // Expected output: 42
    
    console.log(obj.result);
    // Expected output: true
    
    Login or Signup to reply.
  2.   fetch(url)
      .then((response) => response.json())
      .then((values) => {
         return data;
      });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search