gpt4 book ai didi

node.js - 解析器抛出错误时 GraphQL 重定向

转载 作者:搜寻专家 更新时间:2023-10-31 22:39:37 25 4
gpt4 key购买 nike

我正在使用 graphql-server-express构建一个使用 REST API 的 GraphQL 服务器。

我遇到的情况是,当用户未通过身份验证无法访问资源时,REST 调用可能会返回 301 或 401 状态代码。我正在使用在客户端设置并在解析 GraphQL 查询时转发到 REST API 的 cookie。

当发生此类错误时,是否可以向客户端发送 301 重定向以响应对 GraphQL 端点的调用?

我试过类似 res.sendStatus(301) … 的东西在formatError但这并不像graphql-server-express那样有效在此之后尝试设置标题。

我还尝试过将 graphqlExpress 短路像这样的中间件:

export default graphqlExpress((req, res) => {
res.sendStatus(301);
return;
});

虽然客户端收到正确的结果,但服务器仍然打印错误(在本例中为 TypeError: Cannot read property 'formatError' of undefined – 很可能是因为中间件收到空选项)。

有什么好的方法可以让它发挥作用吗?谢谢!

最佳答案

下面是我的实现方式。

在服务器端:

// Setup
export default class UnauthorizedError extends Error {
constructor({statusCode = 401, url}) {
super('Unauthorized request to ' + url);
this.statusCode = statusCode;
}
}

// In a resolver
throw new UnauthorizedError({url});

// Setup of the request handler
graphqlExpress(async (req, res) => ({
schema: ...,
formatError(error) {
if (error.originalError instanceof UnauthorizedError) {
res.status(error.originalError.statusCode);
res.set('Location', 'http://domain.tld/login');
} else {
res.status(500);
}

return error;
},
});

在客户端:

const networkInterface = createNetworkInterface();

networkInterface.useAfter([{
applyAfterware({response}, next) {
if ([401, 403].includes(response.status)) {
document.location = response.headers.get('Location');
} else {
next();
}
}
}]);

在 Apollo Client 2.0 中,您可能可以使用 apollo-link-error在客户端为此。

关于node.js - 解析器抛出错误时 GraphQL 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41281245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com