Skip to content

Commit

Permalink
a
Browse files Browse the repository at this point in the history
  • Loading branch information
wangzhao committed Aug 2, 2018
1 parent 8b67ac8 commit 0567a24
Show file tree
Hide file tree
Showing 8 changed files with 129 additions and 84 deletions.
21 changes: 12 additions & 9 deletions 1.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,19 @@
// console.log(myEmitter.getMaxListeners());
// console.log(myEmitter.eventNames());

var miniToastr = require('mini-toastr');
// var miniToastr = require('mini-toastr');

const toastTypes = {
success: 'success',
error: 'error',
info: 'info',
warn: 'warn'
};
// const toastTypes = {
// success: 'success',
// error: 'error',
// info: 'info',
// warn: 'warn'
// };

miniToastr.init({ types: toastTypes });
// miniToastr.init({ types: toastTypes });

// miniToastr.success({ message: 11 })

console.log(require('./public/api'));

miniToastr.success({ message: 11 })

2 changes: 1 addition & 1 deletion nuxt.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ module.exports = {
}),
// Api middleware
// We add /api/login & /api/logout routes
'~/api/index.js'
'~/api'
],
/*
** Headers of the page
Expand Down
32 changes: 32 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"babel-node": "babel-node --presets=es2015",
"dev": "cross-env BASE_URL='https://postman-echo.com' nuxt ",
"build": "nuxt build",
"start": "cross-env NODE_ENV=production BASE_URL=https://postman-echo.com node server.js",
"start": "cross-env NODE_ENV=production node server.js",
"generate": "nuxt generate",
"lint": "eslint --ext .js,.vue --ignore-path .gitignore .",
"precommit": "npm run lint",
Expand Down Expand Up @@ -40,11 +40,13 @@
"eslint-plugin-vue": "^4.0.0",
"express": "^4.16.3",
"express-session": "^1.15.6",
"fs": "0.0.1-security",
"jquery": "^3.2.1",
"jsdom": "^11.11.0",
"less-loader": "^4.1.0",
"mini-toastr": "^0.8.1",
"node-less": "^1.0.0",
"node-localstorage": "^1.3.1",
"normalize.css": "^8.0.0",
"querystring": "^0.2.0",
"request": "^2.87.0",
Expand Down
46 changes: 26 additions & 20 deletions public/api/index.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,39 @@

var express = require('express');
const router = express.Router();
// Create express router
const router = express.Router()

// Transform req & res to have the same API as express
// So we can use res.status() & res.json()
var app = express();
var app = express()
router.use((req, res, next) => {
Object.setPrototypeOf(req, app.request);
Object.setPrototypeOf(res, app.response);
req.res = res;
res.req = req;
next();
});
Object.setPrototypeOf(req, app.request)
Object.setPrototypeOf(res, app.response)
req.res = res
res.req = req
next()
})
console.log(111, router);

//Add POST - /api/login
// Add POST - /api/login
router.post('/login', (req, res) => {
if (req.body.username == 'demo' && req.body.password == 'demo') {
req.session.authUser = { username: req.body.username };
return res.json({ username: req.body.password });
console.log(111888888);
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" });
});
res.status(401).json({ message: 'Bad credentials' })
})

// Add POST - /api/logout
router.post('/logout', (req, res) => {
delete req.session.authUser;
res.json({ ok: true });
});
//Export the server middleware
return {
delete req.session.authUser
res.json({ ok: true })
})

var middleware = {
path: '/api',
handler: router
};
};
//Export the server middleware
module.exports = middleware;
7 changes: 6 additions & 1 deletion public/middleware/authenticated.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
export default function ({ store, redirect }) {
// if (typeof localStorage === "undefined" || localStorage === null) {
// var LocalStorage = require('node-localstorage').LocalStorage;
// localStorage = new LocalStorage('./scratch');
// }
// if (!store.state.authUser && localStorage.getItem('loginState') == 'false') {
if (!store.state.authUser) {
return redirect('/login');
// return redirect('/login');
}
}
9 changes: 7 additions & 2 deletions public/store/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,17 @@ const store = () => {
},
SET_USER(state, user) {
state.authUser = user;
if (user) {
localStorage.setItem('loginState', true);
} else {
localStorage.setItem('loginState', false);
}
}
},
actions: {
// nuxtServerInit is called by Nuxt.js before server-rendering every page
nuxtServerInit({ commit }, { req }) {
console.log(req.session, req.session.authUser);
console.log(8888, req.session, req.session.authUser);
if (req.session && req.session.authUser) {
commit('SET_USER', req.session.authUser)
}
Expand All @@ -35,7 +40,7 @@ const store = () => {
console.log(data);
commit('SET_USER', data);
},
async logout({commit}){
async logout({ commit }) {
await axios.post('/api/logout');
commit('SET_USER', null);
}
Expand Down
92 changes: 42 additions & 50 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,50 +1,42 @@
// let config = require('./nuxt.config');
// const app = require('express')();
// const { Nuxt, Builder } = require('nuxt');
// const port = process.env.PORT || 3000;


// const nuxt = new Nuxt(config);
// console.log(config);

// // app.use(nuxt);
// if (config.dev) {
// new Builder(nuxt).build().catch(err => {
// console.error(error);
// process.exit(1);
// })
// }

// // console.log(config);

// // app.listen(port, '0.0.0.0').then(()=>{
// // nuxt.showOpen();
// // })

// const express = require('express')
// const request = require('request')
// const app = express()

// app.use('/', function (req, res) {
// const url = 'https://nuxt-auth-routes.glitch.me' + req.url
// req.pipe(request(url)).pipe(res.set('Access-Control-Allow-Origin', '*'))
// });

// app.listen(process.env.PORT || 3001);

// var express = require('express');
// var app = express();

// var cors = require('cors');
// var bodyParser = require('body-parser');

// //enables cors
// app.use(cors({
// 'allowedHeaders': ['sessionId', 'Content-Type'],
// 'exposedHeaders': ['sessionId'],
// 'origin': '*',
// 'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
// 'preflightContinue': false
// }));

// require('./router/index')(app);
const { Nuxt, Builder } = require('nuxt')
const bodyParser = require('body-parser')
const session = require('express-session')
const app = require('express')()

// 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({ error: '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 })
})

// We instantiate Nuxt.js with the options
const isProd = process.env.NODE_ENV === 'production'
const nuxt = new Nuxt({ dev: !isProd })
// No build in production
if (!isProd) {
const builder = new Builder(nuxt)
builder.build()
}
app.use(nuxt.render)
app.listen(3000)
console.log('Server is listening on http://localhost:3000')

0 comments on commit 0567a24

Please sign in to comment.