通过查看
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路由的参数由于
hash路由的参数,会导致
vue-router不起效果,对于使用了
vue-router的前后端同构应用,必须换为
history路由。接口处获取不到
cookie的问题:由于客户端每次请求都会对应地把
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;










