node.js - 为什么我不能从带有 axios 的 graphql 获得可用的响应?
问题描述
我已成功通过服务器进行身份验证,发送了我的 graphql 请求并收到了响应。然而,反应并不完全正确。
这只是简单的nodejs、axios、graphql的情况。我可以通过邮递员或 curl 获得正确的响应,但不能使用节点。我也尝试过 fetch 无济于事。难道我做错了什么?这是针对 producthunt api,api explorer 位于这里
require('dotenv').config()
const axios = require("axios");
const PH_KEY = process.env.PH_KEY;
const PH_SECRET = process.env.PH_SECRET;
const BASE_URL = process.env.BASE_URL;
const AUTH_URL = process.env.AUTH_URL;
const GRAPHQL_URL = process.env.GRAPHQL_URL;
const PH = axios.create({
baseURL: BASE_URL,
responseType: 'json',
headers: {
// 'Accept': 'application/json, text/plain, gzip, deflate, */*',
'Content-Type': 'application/json'
},
})
let TOKEN = 'Bearer '
const getAuth = async () => {
return await PH({
url: AUTH_URL,
method: "post",
data: {
client_id: `${PH_KEY}`,
client_secret: `${PH_SECRET}`,
grant_type: "client_credentials"
}
})
.then((res) => {
console.log('auth status ', res.status)
return res.data.access_token
})
.then((res) => {
TOKEN += res
console.log(TOKEN)
})
.catch((err) => {
console.log(err)
})
}
const getHunt = async () => {
await getAuth()
PH.defaults.headers.common['Authorization'] = TOKEN
return await PH({
url: GRAPHQL_URL,
method: 'post',
data:
{
query: `
query posts {
posts(order: RANKING, first: 1) {
edges {
node {
name
votesCount
user {
name
}
createdAt
}
}
}
}
`
}
})
.then((res) => {return res})
.then((res) => {
console.log(res.data)
return res.data
})
.catch((err) => {
console.log(err)
})
}
const Main = async () => {
await getHunt()
}
Main()
这是我在节点中收到的输出:
[Running] node "/Users/fireinjun/Work/YAC/yac-ph-tophuntfunction/app.js"
auth status 200
Bearer #################################################
{ data: { posts: { edges: [Array] } } }
这就是我所期待的:
{
"data": {
"posts": {
"edges": [
{
"node": {
"name": "Trends by The Hustle",
"votesCount": 125,
"user": {
"name": "Jack Smith"
},
"createdAt": "2019-06-04T07:01:00Z"
}
}
]
}
}
}
解决方案
我错误地访问了数据!显然我需要看到res.data.data.posts.edges[0]
推荐阅读
- json - MailApp+SpreadsheetApp - 将对象属性作为电子邮件主题传递
- vue.js - 无法使用 axios get response 从服务器获取数据
- bootstrap-4 - 如何在 TinyMCE-5 中渲染/预览引导元素?
- python - 无法将样式应用于 Tkinter 滑块
- windows - Microsoft PowerToys 键映射在 Visual Studio 中不起作用
- git - 如何回到 .gitignore 中的上一个目录
- javascript - Vue JS - 如何将单选按钮的选定值保存到本地存储
- r - 使用 R 从 rMarkDown 文件生成 .pdf
- cluster-computing - 无法在集群计算机上安装 rstan
- c# - Cross-Origin Request Blocked:(原因:CORS 请求未成功)