我有一个使用 graphql api 端点的 expo 应用程序。我尝试在每个请求中传递授权令牌,但我的设置似乎没有设置或发送我的授权标头。在我的 graphql.config.yml 中,我可以像这样在此处设置授权标头并且它可以工作:
schema: schema.graphql
extensions:
endpoints:
Dev Backend:
url: http://localhost:8000/graphql
introspect: true
headers:
authorization: "My token"
但在我的实际客户端设置代码中,它没有设置我的授权标头。后端记录的标头如下所示:
Headers({
'content-length': '113',
'content-type': 'application/json; charset=UTF-8',
'host': 'localhost:8000',
'connection': 'Keep-Alive',
'user-agent': 'Apache-HttpClient/4.5.14 (Java/17.0.7)',
'accept-encoding': 'gzip,deflate'
})
对此的任何帮助将不胜感激。
import {ApolloClient, InMemoryCache, ApolloLink, concat} from '@apollo/client';
import {setContext} from '@apollo/client/link/context';
import {getUserSession} from "./session-handler";
import {createUploadLink} from "apollo-upload-client"; // Import AsyncStorage from the correct package
// Create an HTTP link to your GraphQL server
const httpLink = createUploadLink({
uri: 'http://localhost:8000/',
credentials: 'include',
});
const authMiddleware = new ApolloLink((operation, forward) => {
// add the authorization to the headers
operation.setContext(({ headers = {} }) => ({
headers: {
...headers,
authorization: "THIS IS A TEST TOKEN",
}
}));
return forward(operation);
})
const client = new ApolloClient({
cache: new InMemoryCache(),
link: concat(authMiddleware, httpLink),
});
export {
client
};
我做了一些挖掘,问题与前端和后端代码有关。我的 JWT 密钥未以 Base64 进行编码(因此我将其编码为 Base64),并且我没有在前端令牌的开头传递“Bearer”。