【发布时间】:2019-09-17 17:45:38
【问题描述】:
我正在努力使用 axios 执行我的第一个 graphQl 查询。
应用堆栈是前端的 Gatsby,后端是 Symfony 的 API 平台。
我确实在 SO 和博客文章中检查了其他一些类似的问题,但没有运气。
问题是查询在 graphiQl 上有效,如果我尝试使用 fetch API 执行,它也有效。
此代码在sagas.js内
这里是
const api = (data) => {
return axios({
method: 'POST',
url: API_ROOT_GRAPHQL,
data,
headers: { 'Content-Type': 'application/json' },
}).then((response) => {
console.log('response axios', response);
return response.data;
});
};
function* getUserProfile(action) {
const userId = `"/api/users/${action.payload.userId}"`;
const queryQl = {
query: `{
user(id: ${userId}) {
id
username
name
email
roles
}
}`,
};
try {
yield put({
type: GET_USER_PROFILE_INIT,
});
const data = yield call(api, queryQl);
console.log('data user profile', data);
yield put({
type: GET_USER_PROFILE_OK,
data: data.user,
});
} catch (error) {
正如您在下面看到的,抛出错误:Cannot return null for non nullable field
问题是下面的 fetch 查询可以完美运行 - graphiql 也是如此 - 所以我想知道这一定是我的 axios 请求中的一些配置问题。
我还检查了发布到 API 的数据是否与 axios et fetch 相同,如下 Firefox 开发工具 Network-> 参数:
query { user(id: "/api/users/1") { id username name email roles } }
const apiQl = (queryQl) => {
return fetch('http://localhost:8000/api/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(queryQl),
}).then((response) => {
return response.json();
}).then((response) => {
console.log('rsponse fetch', response);
return response.data;
});
};
编辑:axios 的请求标头
【问题讨论】:
-
当控制台清楚地向用户显示错误和 null 时,它是如何“完美运行”的?
-
查看图片顶部。它说“响应 axios”,来自您可以在 axios 函数上看到的 console.log。我想显示 axios 错误的输出。 fetch 函数确实工作得很好,所以没有必要显示它的输出。
-
您的架构在某处将
username声明为您的用户类型上的不可为空字段(可能是String!),并且您的后端为响应该查询而提供的数据不符合该条件。这可能是因为您没有设置用户 ID 或其他东西,但这几乎可以肯定与 axios 无关。出于好奇,您为什么要使用生成器来获取用户资料?对于这样一个常见的例程,这段代码似乎过于复杂了。 -
@coreyward。谢谢。
username确实是不可为空的,但同样的限制对于来自graphiql或来自fetch()的查询有效并且它们不会失败。所以我的猜测是某些特定于axios的配置。不确定我是否同意过度复杂化。查询功能非常简单,然后它是传奇的一部分,这是非常样板。 -
@BernardA 你没有分享任何显示你和
fetch做同样事情的东西,你也没有分享请求数据。告诉我们这些工作有效,而事实并非如此,我们就无法帮助您找到代码中的错误。
标签: javascript reactjs graphql axios gatsby