[英]How to fetch data from Apollo-Server without using React in nodeJs?
我想知道如果我可以在不使用 React 的情況下從 Apollo-Server (GraphQL) 獲取數據,我搜索了一些基於 fetch 但 node-fetch 不起作用的教程這是我用於獲取數據的代碼
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));
}
查詢是:
query=`
query Blogs {
blogs {
title
content
imageUrl
}
}
編輯
Axios 運行良好:這是最終代碼:
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
}
嘗試使用 axios 獲取數據並設置 headers = {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.