Reactjs 如何在React Apollo中将头添加到HttpLink
我想在graphql查询中输入令牌。我必须把身份验证令牌放在哪里 以下是我在apollo.js中的代码:Reactjs 如何在React Apollo中将头添加到HttpLink,reactjs,graphql,token,apollo,Reactjs,Graphql,Token,Apollo,我想在graphql查询中输入令牌。我必须把身份验证令牌放在哪里 以下是我在apollo.js中的代码: import { withData } from 'next-apollo' import { HttpLink } from 'apollo-link-http' export const config = { link: new HttpLink({ uri: 'http://localhost:8000/graphql/', // Server URL (must be
import { withData } from 'next-apollo'
import { HttpLink } from 'apollo-link-http'
export const config = {
link: new HttpLink({
uri: 'http://localhost:8000/graphql/', // Server URL (must be absolute)
opts: {
credentials: 'include', // Additional fetch() options like `credentials` or `headers`
}
})
}
export default withData(config)
我就是这样提问的:
const MYJOBS = gql`
{
myJobs {
role {
name
}
school {
name
}
}
}
`
<Query query={MYJOBS}>
根据的文档,我们可以通过setContext这样做-安装apollo链接上下文并从文件顶部的“apollo链接上下文”导入{setContext}:
const authLink = setContext((_, { headers }) => {
// get the authentication token from whereever it exists - This is your choice.
const token = localStorage.getItem('token');
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
}
});
const httpLink = new HttpLink({
uri: 'http://localhost:8000/graphql/', // Server URL (must be absolute)
opts: {
credentials: 'include', // Additional fetch() options like `credentials` or `headers`
}
})
然后在您的配置中:
export const config = {
link: authLink.concat(httpLink)
}
这将在我们进行的每个查询中自动包含授权/凭据
希望这会有所帮助。根据的文档,我们可以通过setContext这样做-安装apollo链接上下文并从文件顶部的“apollo链接上下文”导入{setContext}:
const authLink = setContext((_, { headers }) => {
// get the authentication token from whereever it exists - This is your choice.
const token = localStorage.getItem('token');
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
}
});
const httpLink = new HttpLink({
uri: 'http://localhost:8000/graphql/', // Server URL (must be absolute)
opts: {
credentials: 'include', // Additional fetch() options like `credentials` or `headers`
}
})
然后在您的配置中:
export const config = {
link: authLink.concat(httpLink)
}
这将在我们进行的每个查询中自动包含授权/凭据
希望这会有所帮助。最后,我的朋友建议为查询添加上下文,结果成功了
<Query
query={ME}
context={{
headers: {
authorization: JWT ${localStorage.getItem('token')}
}
}} >
最后,我的朋友建议为查询添加上下文,结果成功了
<Query
query={ME}
context={{
headers: {
authorization: JWT ${localStorage.getItem('token')}
}
}} >
以下是使用@apollo/client的新方法:
以下是使用@apollo/client的新方法: