简体   繁体   English

如何重新运行Vue.js ApolloClient中间件?

[英]How can I re-run Vue.js ApolloClient middleware?

In my main.js I have some code that checks for the existence of a localStorage item. 在我的main.js我有一些代码可以检查是否存在localStorage项。 If it has it, it will add an Authorization header via middleware to the ApolloClient setup. 如果有,它将通过中间件向ApolloClient设置添加Authorization标头。

However, if a localStorage item is later added , it's not present in the middleware of main.js . 但是,如果稍后添加了localStorage项,则它不会出现在main.js的中间件中。 A full page refresh is therefore required in order to get it to pick it up / know of its existence. 因此,需要进行整页刷新才能使其获取/了解其存在。

How can I run main.js again (if that's even the solution) from a method in say, a component that signs the user in? 如何从一个方法中再次运行main.js (如果这甚至是解决方案),例如,一个用户签名的组件?

Here's my main.js : 这是我的main.js

import Vue from 'vue'
import ApolloClient, { createNetworkInterface } from 'apollo-client'
import VueApollo from 'vue-apollo'
import App from './App'
import router from './router'
import store from './store'

const networkInterface = createNetworkInterface({ uri: 'https://api.graph.cool/simple/v1/MY-ID-HERE' })
const requestToken = localStorage.getItem('TOKEN')

networkInterface.use([{
  applyMiddleware (req, next) {
    if (!req.options.headers) {
      req.options.headers = {}
    }
    req.options.headers['Authorization'] = requestToken ? `Bearer ${requestToken}` : null
    next()
  }
}])

const apolloClient = new ApolloClient({
  networkInterface
})

const apolloProvider = new VueApollo({
  defaultClient: apolloClient
})

Vue.use(VueApollo)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  template: '<App />',
  components: {
    App
  },
  apolloProvider,
  router,
  store
})

Hopefully you can understand what I'm trying to do? 希望你能理解我想要做什么?

Thanks 谢谢

I believe you need to move your requestToken declaration inside the applyMiddleware function. 我相信你需要在applyMiddleware函数中移动你的requestToken声明。 This way, you'll check local storage for a token every time a request is made. 这样,每次发出请求时,您都会检查本地存储是否有令牌。 Otherwise, it's only checked once, when the page is loaded and you end up seeing the behavior you described. 否则,它只会检查一次,当页面加载并且您最终看到您描述的行为时。

networkInterface.use([{   applyMiddleware (req, next) {
    const requestToken = localStorage.getItem('TOKEN')
    if (!req.options.headers) {
      req.options.headers = {}
    }
    req.options.headers['Authorization'] = requestToken ? `Bearer ${requestToken}` : null
    next()   } }])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM