如何解决在 Nuxt.js 中发送每个请求时,如何向 apollo 上的数据添加对象?
在 Nuxt.js 中发送每个请求时,如何向 apollo 上的数据添加对象?我有一个对象,它在每个请求上发送并且也是静态的。所以,我认为应该有类似 apollo 的 axios 拦截器的东西,但我什么也没找到。感谢您的帮助。
解决方法
你可以有这种配置
/plugins/nuxt-apollo-config.js
import { setContext } from 'apollo-link-context'
import { from } from 'apollo-link'
import { createHttpLink } from '@apollo/client/core'
export default ({ $config: { baseUrlGraphql } }) => {
const headersConfig = setContext(() => ({
credentials: 'same-origin',headers: {
Authorization: 'tasty-token','specific-token': 'static_token',// you can put your static data here for example
},}))
return {
link: from([
headersConfig,// anotherCustomLink,createHttpLink({
credentials: 'include',uri: baseUrlGraphql,fetch: (uri,options) => {
return fetch(uri,options)
},}),]),}
}
然后您可以阅读此文档以了解整个链接的工作原理:https://www.apollographql.com/docs/react/api/link/introduction/
那样,您可以在链中添加一个链接,就像我上面的代码片段(名为 anotherCustomLink
)一样,然后访问/修改操作
const anotherCustomLink = (operation,forward) => {
console.log('what is the current context?',operation.getContext())
operation.setContext(...)
return forward(operation).map((data) => {
...
return data
})
}
编辑:作为起点,您应该将其放入您的 nuxt.config.js
文件
export default {
...
apollo: {
clientConfigs: {
// recommended: use a file to declare the client configuration (see below for example)
default: '@/plugins/nuxt-apollo-config.js',},}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。