我有一个:
前端:React,Next.js。使用阿波罗客户端。
后端:NodeJs,具有GraphQL端点的Express服务器。
我将一个cookie应用于GraphQL apollo客户端,这是实例化的代码。
({ ctx, headers, initialState }) =>
new ApolloClient({
uri: "http://localhost:4000/graphql",
cache: cache,
credentials: 'include',
headers: {
authorization: Cookies.get('token') ? `Bearer ${Cookies.get('token')}` : ""},
typeDefs,
resolvers
}));
当我在React组件中使用useQuery时,我向后端发送了一个graphQL请求。我设置了中间件来通过检查令牌来验证请求。代码:
export let checkToken = (req : any, res : any, next : any) => {
let token = req.headers['authorization']; // I also tried req.headers.authorization
if (token.startsWith('Bearer ')) {
token = token.slice(7, token.length);
}
if (token) {
jwt.verify(token, config.cookieKey, (err : any, decoded : any) => {
if (err) {
Logger.info("Token in request is not valid.");
return res.json({
success: false,
message: 'Token is not valid'
});
} else {
Logger.info("Token in request is valid.");
req.decoded = decoded;
next();
}
});
} else {
Logger.info("No token in request found.");
return res.json({
success: false,
message: 'Auth token is not supplied'
});
}
};
问题在于,一旦到达后端,req.headers.authorization就没有定义。我已经在客户端之前通过控制台记录了cookie令牌,并且它确实返回了cookie。
CORS EDIT
app.use(function(_req, res, next) {
res.header("Access-Control-Allow-Origin", `${config.frontend_url}`);
res.header('Access-Control-Allow-Methods', "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Credentials", "true");
res.header('Access-Control-Allow-Headers', "Access-Control-Allow-Origin, Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization");
next();
});
Console.log(必需的标题)编辑
{ accept: '*/*',
'content-type': 'application/json',
authorization: '',
'content-length': '185',
'user-agent': 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)',
'accept-encoding': 'gzip,deflate',
connection: 'close',
host: 'localhost:4000' }
{ accept: '*/*',
'content-type': 'application/json',
authorization: '',
'content-length': '185',
'user-agent': 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)',
'accept-encoding': 'gzip,deflate',
connection: 'close',
host: 'localhost:4000' }