feeling
After several Attempts on Saturday and Sunday, we finally solved the common problems in server rendering. When SEO is no longer a problem, maybe it is the real spring for us to work on the front end, which also encountered some small problems. Nuxt.js official is still very helpful, after the issue is very active to help, thanks again to the NuxT.js development team.
Routing authentication
The first obstacle is the authentication problem when landing, how to save the token to the local. Officially, express-Session is used to solve this problem, but doing so also requires nodeJS to be used on the back end, which our company uses in PHP. Then I thought maybe cookie could try, so here’s what I did:
app.post('/api/login'.function (req, res) {
// The backend authenticates the user information and returns the token
async function login () {
const { data } = await axiosServer.post('/login', req.body)
return data
}
login().then(function (data) {
// Store the token in the cookie
const { token } = data
if (token) {
res.cookie('token', token, {
maxAge: 60000 * 60 * 24})}// Return intact
return res.json(data)
})
})
Copy the code
I forwarded the login request with nodeJS, and passed the data submitted by the user to the back end. The token returned by the back end was set in the cookie, and then the data was returned to the front end. Then the front end used VUex to save the token state, so that the token exists in the cookie and memory. The refresh page is also normal for the front-end storage token:
async nuxtServerInit ({ dispatch, commit }, { req, res }) {
if(req.cookies && req.cookies. Token) {// Store token commit(req.cookies && req.cookies.'SET_USER', req.cookies.token)
}
},
// SET_USER
SET_USER (state, token) {
state.token = token
},
Copy the code
So the problem is solved, and all data that needs to be stored locally can be solved in this way
Render the data within the component
Another minor issue is how the data in components is rendered. In nuxt.js, only the components in the page have fetch and asyncData methods. So if the components in the page need to request data, we cannot render it. To solve this problem, we need to initialize the data in nuxtServerInit method.
Async nuxtServerInit ({dispatch, commit}, {req, res}) {// Initialize await dispatch('ADMIN_INFO')
await dispatch('TAGS')
await dispatch('ARCHIVES')}Copy the code
The data in the component is rendered successfully
Use of filters
The plugins in NuxT.js are designed with a personal touch and can’t be simpler to use. Create a new filters.js inside your plugins. The filters can be played like this:
import Vue from 'vue'// Time formattingexport function formatDate (date, fmt) {
let newDate = new Date(date)
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.The $1, (newDate.getFullYear() + ' ').substr(4 - RegExp.The $1.length))
}
let o = {
'M+': newDate.getMonth() + 1,
'd+': newDate.getDate(),
'h+': newDate.getHours(),
'm+': newDate.getMinutes(),
's+': newDate.getSeconds()
}
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + ' '
fmt = fmt.replace(RegExp.The $1, (RegExp.The $1.length === 1) ? str : padLeftZero(str))
}
}
return fmt
}
let filters = {
formatDate
}
Object.keys(filters).forEach(key => {
Vue.filter(key, filters[key])
})
export default filters
Copy the code
Register with nuxt.config.js:
plugins: [
'~plugins/filters.js'
]
Copy the code
Happy can be used in a component like this:
<! - time format -- -- > < div > < span > {{date | formatDate ('yyyy-MM-dd')}}</span>
</div>
Copy the code
The middleware
For example, when a user is not logged in and accesses the page that needs authentication through the route, we can customize some errors:
// auth.js
export default function({store, error}) {// You can receive error messages via the component's propsif(! store.state.token) { error({ message:'Cookie invalid or not logged in, please log in after operation',
statusCode: 403
})
}
}
Copy the code
Using this middleware in components:
export default {
middleware: 'auth'Fetch ({redirect, store}) {if(! store.state.token) { redirect('/login')}}}Copy the code
Multi-level routing is nested
Officially, this situation is rarely used, but I found that it is used a lot. For example, different categories have different pages, so both categories and pages are dynamically routed, as shown in the figure:
Project deployment
Back in August, I wrote a couple of articles about how to deploy nodeJS projects. When I look back, I found that I was pretty good at it. As time went on, I fixed some bugs, found some bugs, and the overall writing was too messy. So I took a day to practice and record on the new server, and summarized the above articles with gitbook. I did not expand it here, because it was too long, and added the relevant content of automatic deployment
The project practice
This small project was written by me a few months ago. In recent months, I refactored with NuxT.js. The front-end used NuxT.js + vuex, the back-end used Nodejs + MongoDB, and I wrote a MarkDown editor with Vue to support image uploading and server-side rendering.
Home page
The editor
GitHub
gitbook