| 
                         对于旧项目迁移到SSR肯定会经历的问题,一般为在项目入口处或是created、beforeCreate生命周期使用了DOM操作,或是获取了location对象,通用的解决方案一般为判断执行环境,通过typeof window是否为'undefined',如果遇到必须使用location对象的地方用于获取url中的相关参数,在ctx对象中也可以找到对应参数。 
    -  vue-router报错Uncaught TypeError: _Vue.extend is not _Vue function,没有找到_Vue实例的问题:
 
 
通过查看Vue-router源码发现没有手动调用Vue.use(Vue-Router);。没有调用Vue.use(Vue-Router);在浏览器端没有出现问题,但在服务端就会出现问题。对应的Vue-router源码所示: 
- VueRouter.prototype.init = function init (app /* Vue component instance */) {  
 -     var this$1 = this;  
 -   process.env.NODE_ENV !== 'production' && assert(  
 -     install.installed,  
 -     "not installed. Make sure to call `Vue.use(VueRouter)` " +  
 -     "before creating root instance."  
 -   );  
 -   // ...  
 - } 
 
  
由于hash路由的参数,会导致vue-router不起效果,对于使用了vue-router的前后端同构应用,必须换为history路由。 
由于客户端每次请求都会对应地把cookie带给接口侧,而服务端Web Server Frame作为代理服务器,并不会每次维持cookie,,所以需要我们手动把 
cookie透传给接口侧,常用的解决方案是,将ctx挂载到全局状态中,当发起异步请求时,手动带上cookie,如下代码所示: 
- // createStore.js  
 - // 在创建全局状态的函数`createStore`时,将`ctx`挂载到全局状态  
 - export function createStore({ ctx }) {  
 -     return new Vuex.Store({  
 -         state: {  
 -             ...state,  
 -             ctx,  
 -         }, 
 -          getters,  
 -         actions,  
 -         mutations,  
 -         modules: {  
 -             // ...  
 -         },  
 -         plugins: debug ? [createLogger()] : [],  
 -     });  
 - } 
 
  
当发起异步请求时,手动带上cookie,项目中使用的是Axios: 
- // actions.js  
 - // ...  
 - const actions = {  
 -   async getUserInfo({ commit, state }) {  
 -     let requestParams = {  
 -       params: {  
 -         random: tool.createRandomString(8, true),  
 -       },  
 -       headers: {  
 -         'X-Requested-With': 'XMLHttpRequest',  
 -       },  
 -     };  
 -     // 手动带上cookie  
 -     if (state.ctx.request.headers.cookie) {  
 -       requestParams.headers.Cookie = state.ctx.request.headers.cookie;  
 -     }  
 -     // ...  
 -     let res = await Axios.get(`${requestUrlOrigin}${url.GET_A}`, requestParams);  
 -     commit(globalTypes.SET_A, {  
 -       res: res.data,  
 -     });  
 -   }  
 - };  
 - // ... 
 
  
    -  接口请求时报connect ECONNREFUSED 127.0.0.1:80的问题
 
                         (编辑:91站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |