import Vue from 'vue'; import Vuex from 'vuex'; import user from './modules/user'; import { COOKIE_KEY } from '~/assets/js/constant.js'; Vue.use(Vuex); const store = () => new Vuex.Store({ modules: { user }, actions: { async nuxtServerInit({ commit, dispatch }, { req, app }) { if (req.headers.cookie) { let parsedResult = {}; req.headers.cookie.split(';').forEach(cookie => { const currentCookie = cookie.split('='); parsedResult[currentCookie[0].trim()] = (currentCookie[1] || '').trim(); }); const userInfo = { name: parsedResult[COOKIE_KEY.NAME], token: parsedResult[COOKIE_KEY.TOKEN] }; commit('user/setUserInfo',userInfo); } } } }); export default store;
中间件代码
export default function({ store, error, redirect }) { if (!store.state.user.userInfo.token || !store.state.user.userInfo.name) { // error({ // message: 'You are not connected', // statusCode: 403 // }) redirect('https://www.jb51.net/'); } }
nginx部署
npm run build
选择build以后的四个文件: .nuxt, static, nuxt.config.js, package.json上传到服务器。
pm2 pm2 start npm --name 'package.json.name' -- run start
nginx配置
查看网页源代码可以看到:
server{ listen 3000; server_name felix12345.club; gzip on; gzip_buffers 32 4K; gzip_comp_level 6; gzip_min_length 100; gzip_types application/javascript text/css text/xml; gzip_disable "MSIE [1-6]\."; gzip_vary on; proxy_buffer_size 64k; proxy_buffers 32 32k; proxy_busy_buffers_size 128k; location / { root /data/ww/nuxt; proxy_pass :3002; proxy_set_header X-Real-IP $remote_addr; } }
这样,使用Nuxt.js实现了一个服务端渲染的简易博客。
在线访问地址: :3000/article/