未从graphql发送响应时如何从apollo客户端访问状态代码

时间:2018-08-04 08:46:09

标签: graphql

我有一个使用JWT令牌的apollo-graphql堆栈。对于每个请求,我都会验证JWT令牌并发送带有状态代码401的“无效令牌”消息。

代码如下所示

const authMiddleware = async (req, res, next) => {
    let authHeader = req.headers['x-token'];
    let refreshHeader = req.headers['x-refresh-token'];

    console.log('in middleware');
    /**
     * If tokens are not provided
     * access handling is done in each route
     * */
    if (!authHeader || !refreshHeader || authHeader.split(' ')[0] !== 'Bearer' || refreshHeader.split(' ')[0] !== 'Bearer') {
        req.user = {};
        next();

        return;
    }

    let authToken = authHeader.split(' ')[1];
    let refreshToken = refreshHeader.split(' ')[1];

    /**
     * Incorrect refresh or auth token
     * */
    if (!authToken || !refreshToken) {
        console.log('no token');

        res.status(401).send('Invalid Token');
        return;
    }

    try {
        console.log('verifying');

        let payload = await verifyToken(authToken, process.env.JWT_AUTH_SECRET);

        req.user = payload;

        next();

    } catch (e) {
        res.status(401).send('Invalid Token');
        next();
    }
};

问题是我无法在apollo客户端上检测到401状态代码,因为该错误不是在graphql中间件中引发的,而是在此之前的中间件中引发的。

我在下面尝试过,但是networkError是undefined

const tokenVerifyLink = onError(({graphQLErrors, networkError, operation, forward}) => {
    console.log('error');
    console.log(networkError);
    if(networkError.statusCode === 401){
        console.log(networkError);
    }
});

在快递服务器的graphql中间件中未引发错误时,如何访问状态代码?

0 个答案:

没有答案