node.js - 带有 RESTful 的 GraphQL 返回空响应
问题描述
我正在GraphQL
与REST
端点连接,我确认每当我调用http://localhost:3001/graphql
它时它都会击中REST
端点并且它正在JSON
向服务器返回响应GraphQL
,但是我从GraphQL
服务器得到一个空响应,GUI
如下所示:
{
"data": {
"merchant": {
"id": null
}
}
}
查询(手动解码):
http://localhost:3001/graphql?query={
merchant(id: 1) {
id
}
}
下面是我的GraphQLObjectType
样子:
const MerchantType = new GraphQLObjectType({
name: 'Merchant',
description: 'Merchant details',
fields : () => ({
id : {
type: GraphQLString // ,
// resolve: merchant => merchant.id
},
email: {type: GraphQLString}, // same name as field in REST response, so resolver is not requested
mobile: {type: GraphQLString}
})
});
const QueryType = new GraphQLObjectType({
name: 'Query',
description: 'The root of all... queries',
fields: () => ({
merchant: {
type: merchant.MerchantType,
args: {
id: {type: new GraphQLNonNull(GraphQLID)},
},
resolve: (root, args) => rest.fetchResponseByURL(`merchant/${args.id}/`)
},
}),
});
来自端点的响应REST
(我也尝试使用 JSON 中的单个对象而不是 JSON 数组):
[
{
"merchant": {
"id": "1",
"email": "a@b.com",
"mobile": "1234567890"
}
}
]
REST调用使用node-fetch
function fetchResponseByURL(relativeURL) {
return fetch(`${config.BASE_URL}${relativeURL}`, {
method: 'GET',
headers: {
Accept: 'application/json',
}
})
.then(response => {
if (response.ok) {
return response.json();
}
})
.catch(error => { console.log('request failed', error); });
}
const rest = {
fetchResponseByURL
}
export default rest
GitHub:https
://github.com/vishrantgupta/graphql
JSON端点(虚拟):https ://api.myjson.com/bins/8lwqk
编辑:添加node.js
标签,可能是 promise 对象的问题。
解决方案
您的fetchResponseByURL函数获取空字符串。
我认为主要问题是您使用错误的函数来获取您的 JSON 字符串,请尝试安装request-promise并使用它来获取您的 JSON 字符串。
https://github.com/request/request-promise#readme
就像是
var rp = require('request-promise');
function fetchResponseByURL(relativeURL) {
return rp('https://api.myjson.com/bins/8lwqk')
.then((html) => {
const data = JSON.parse(html)
return data.merchant
})
.catch((err) => console.error(err));
// .catch(error => { console.log('request failed', error); });
}
推荐阅读
- bash - 你如何抑制期望脚本中的密码提示?
- reactjs - 反应-Redux。我可以查看我的数组状态但无法映射它
- swagger - 获取 REST API 的 Swagger/OAS 定义
- java - 在Java中从文件迭代到二维数组?
- javascript - 从人员选择器中获取值并将其添加到人员列中的列表中
- python - 为什么 pandas 的 style.format 在 spyder 中不起作用?
- android - 在 Android 中编译 Ionic (Angular) 应用程序时出现问题
- netlogo - Netlogo 要求海龟到达第一个目的地后去第二个目的地
- c++ - 不同核心上的观察者设计模式说(观察者和主题作为单独的进程)(C++)
- django - docker 镜像中的客户端如何知道另一个 docker 镜像中的服务器的 IP 地址?