Home > Mobile >  How to fetch data from Apollo-Server without using React in nodeJs?
How to fetch data from Apollo-Server without using React in nodeJs?

Time:09-17

I was wondering If I can fetch data from Apollo-Server (GraphQL) without using React, I searched for some tutorials which based on fetch but node-fetch didn't work that way here is my code for fetching data

const getData = (query)=>{

return fetch("http://localhost:4000/graphql",{
    method: "POST",
    headers: {
        "Content-Type" : "application/json",
        "Accept" : "application/json"
    },
    body: JSON.stringify(query)
}).then(response=>response.json()).then(data=>{
    return data
}).catch(err=>console.log(err));

}

and the query was:

query=`
query Blogs {
    blogs {
      title
      content
      imageUrl
    }
  }

EDIT

Axios worked very well! here is the final code:

const getData = async () => {

const endpoint = "http://localhost:4000/graphql";
const headers = {
    "content-type": "application/json",
};
const graphqlQuery = {
    "query": `query Blogs {
    blogs {
      title
      content
      imageUrl
    }
  }
`,
};

const response = await axios.post(endpoint, graphqlQuery, {
    method: 'post',
    headers: headers,
});

console.log(response.data.data.blogs); // data
console.log(response.errors); // errors if any

}

CodePudding user response:

Try to use axios for fetching data and set headers = {}

  • Related