Update example to not use a custom server anymore

This commit is contained in:
Sébastien Chopin 2017-07-08 18:04:47 +02:00
parent f490652d18
commit 5c8ac31b3c
6 changed files with 92 additions and 89 deletions

View File

@ -0,0 +1,38 @@
const express = require('express')
module.exports = function () {
// Create express router
const router = express.Router()
var app = express()
// Transform req & res to have the same API as express
// So we can use res.status() & res.json()
router.use((req, res, next) => {
Object.setPrototypeOf(req, app.request)
Object.setPrototypeOf(res, app.response)
req.res = res
res.req = req
next()
})
// Add POST - /api/login
router.post('/login', (req, res) => {
if (req.body.username === 'demo' && req.body.password === 'demo') {
req.session.authUser = { username: 'demo' }
return res.json({ username: 'demo' })
}
res.status(401).json({ message: 'Bad credentials' })
})
// Add POST - /api/logout
router.post('/logout', (req, res) => {
delete req.session.authUser
res.json({ ok: true })
})
// Add router to /api
this.addServerMiddleware({
path: '/api',
handler: router
})
}

View File

@ -1,3 +1,6 @@
const bodyParser = require('body-parser')
const session = require('express-session')
module.exports = {
head: {
title: 'Auth Routes',
@ -9,5 +12,26 @@ module.exports = {
},
build: {
vendor: ['axios']
}
},
/*
** Add server middleware
** Nuxt.js uses `connect` module as server
** So most of express middleware works with nuxt.js server middleware
*/
serverMiddleware: [
// body-parser middleware
bodyParser.json(),
// session middleware
session({
secret: 'super-secret-key',
resave: false,
saveUninitialized: false,
cookie: { maxAge: 60000 }
})
],
/*
** Add our custom module
** In this module we add /api/login & /api/logout routes
*/
modules: ['~/api']
}

View File

@ -1,17 +1,15 @@
{
"name": "auth-routes",
"description": "",
"dependencies": {
"axios": "^0.16.1",
"body-parser": "^1.17.2",
"cross-env": "^5.0.0",
"express": "^4.15.3",
"express-session": "^1.15.3",
"nuxt": "^1.0.0-alpha1"
"nuxt": "latest"
},
"scripts": {
"dev": "node server.js",
"dev": "nuxt",
"build": "nuxt build",
"start": "cross-env NODE_ENV=production node server.js"
"start": "nuxt start"
}
}

View File

@ -28,22 +28,25 @@ export default {
}
},
methods: {
login () {
this.$store.dispatch('login', {
username: this.formUsername,
password: this.formPassword
})
.then(() => {
async login () {
try {
await this.$store.dispatch('login', {
username: this.formUsername,
password: this.formPassword
})
this.formUsername = ''
this.formPassword = ''
this.formError = null
})
.catch((e) => {
} catch(e) {
this.formError = e.message
})
}
},
logout () {
this.$store.dispatch('logout')
async logout () {
try {
await this.$store.dispatch('logout')
} catch (e) {
this.formError = e.message
}
}
}
}

View File

@ -1,56 +0,0 @@
const Nuxt = require('nuxt')
const bodyParser = require('body-parser')
const session = require('express-session')
const app = require('express')()
const host = process.env.HOST || '127.0.0.1'
const port = process.env.PORT || '3000'
// Body parser, to access req.body
app.use(bodyParser.json())
// Sessions to create req.session
app.use(session({
secret: 'super-secret-key',
resave: false,
saveUninitialized: false,
cookie: { maxAge: 60000 }
}))
// POST /api/login to log in the user and add him to the req.session.authUser
app.post('/api/login', function (req, res) {
if (req.body.username === 'demo' && req.body.password === 'demo') {
req.session.authUser = { username: 'demo' }
return res.json({ username: 'demo' })
}
res.status(401).json({ message: 'Bad credentials' })
})
// POST /api/logout to log out the user and remove it from the req.session
app.post('/api/logout', function (req, res) {
delete req.session.authUser
res.json({ ok: true })
})
// Import and Set Nuxt.js options
let config = require('./nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
// Init Nuxt.js
new Nuxt(config)
.then((nuxt) => {
// nuxt middlware
app.use(nuxt.render)
// Build only in dev mode
if (config.dev) {
nuxt.build()
.catch((error) => {
console.error(error) // eslint-disable-line no-console
process.exit(1)
})
}
// Listen the server
app.listen(port, host)
console.log('Server listening on ' + host + ':' + port) // eslint-disable-line no-console
})

View File

@ -11,31 +11,27 @@ export const mutations = {
}
export const actions = {
// nuxtServerInit is called by Nuxt.js before server-rendering every page
nuxtServerInit ({ commit }, { req }) {
if (req.session && req.session.authUser) {
commit('SET_USER', req.session.authUser)
}
},
login ({ commit }, { username, password }) {
return axios.post('/api/login', {
username,
password
})
.then((res) => {
commit('SET_USER', res.data)
})
.catch((error) => {
if (error.response.status === 401) {
async login ({ commit }, { username, password }) {
try {
const { data } = await axios.post('/api/login', { username, password })
commit('SET_USER', data)
} catch (error) {
if (error.response && error.response.status === 401) {
throw new Error('Bad credentials')
}
})
throw error
}
},
logout ({ commit }) {
return axios.post('/api/logout')
.then(() => {
commit('SET_USER', null)
})
async logout ({ commit }) {
await axios.post('/api/logout')
commit('SET_USER', null)
}
}