Я хотел ввести токен в свои запросы 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 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}>





Согласно документации аполлон-графql, мы можем сделать это с помощью setContext — установить apollo-link-context и выполнить import { setContext } from 'apollo-link-context' вверху вашего файла:
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)
}
Это будет автоматически включать авторизацию/учетные данные при каждом запросе, который мы делаем.
Надеюсь, это полезно.
Наконец, мой друг предложил добавить context к Query, и это сработало!
<Query
query = {ME}
context = {{
headers: {
authorization: JWT ${localStorage.getItem('token')}
}
}} >
Вот новый подход с использованием @apollo/client: