Skip to content

Commit

Permalink
api
Browse files Browse the repository at this point in the history
  • Loading branch information
wangzhao committed Aug 2, 2018
1 parent 6dd5e53 commit 4df1342
Show file tree
Hide file tree
Showing 8 changed files with 164 additions and 61 deletions.
5 changes: 5 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"presets": [
"env"
]
}
100 changes: 50 additions & 50 deletions nuxt.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,48 +11,48 @@ module.exports = {
// ['~/modules/simple.js', { token: '123456' }],
// '@gauseen/nuxt-proxy',
],
proxy: [
[
'/api',
{
target: 'https://nuxt-auth-routes.glitch.me',
pathRewrite: (path, req, res) => {
if (req.method == "GET") {
var pathname = req._parsedUrl.pathname.replace(/^\/api\//, '')
var queryObj = querystring.parse(req._parsedUrl.query)
// var d = makeSign(app_key, app_secret, req.method, pathname, queryObj).query;
var d = makeSign('', '', req.method, pathname, queryObj).query;
return '/' + pathname + '?' + querystring.stringify(d)
}
return path.replace('/api', '')
},
onProxyReq: (proxyReq, req, res) => {
if (req.method == "POST" && req.body) {
// proxy: [
// [
// '/api',
// {
// target: 'https://nuxt-auth-routes.glitch.me',
// pathRewrite: (path, req, res) => {
// if (req.method == "GET") {
// var pathname = req._parsedUrl.pathname.replace(/^\/api\//, '')
// var queryObj = querystring.parse(req._parsedUrl.query)
// // var d = makeSign(app_key, app_secret, req.method, pathname, queryObj).query;
// var d = makeSign('', '', req.method, pathname, queryObj).query;
// return '/' + pathname + '?' + querystring.stringify(d)
// }
// return path.replace('/api', '')
// },
// onProxyReq: (proxyReq, req, res) => {
// if (req.method == "POST" && req.body) {

// Remove body-parser body object from the request
var queryObj = req.body
if (req.body) delete req.body;
// // Remove body-parser body object from the request
// var queryObj = req.body
// if (req.body) delete req.body;

var pathname = req._parsedUrl.pathname.replace(/^\/api\//, '')
var body = makeSign(app_key, app_secret, req.method, pathname, queryObj).query;
// var pathname = req._parsedUrl.pathname.replace(/^\/api\//, '')
// var body = makeSign(app_key, app_secret, req.method, pathname, queryObj).query;

body = Object.keys(body).map(function (key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(body[key])
}).join('&');
// body = Object.keys(body).map(function (key) {
// return encodeURIComponent(key) + '=' + encodeURIComponent(body[key])
// }).join('&');

// // Update header
proxyReq.setHeader('content-type', 'application/x-www-form-urlencoded');
proxyReq.setHeader('content-length', body.length || 0);
// // // Update header
// proxyReq.setHeader('content-type', 'application/x-www-form-urlencoded');
// proxyReq.setHeader('content-length', body.length || 0);

// // Write out body changes to the proxyReq stream
proxyReq.write(body);
proxyReq.end();
}
}
}
],
// // // Write out body changes to the proxyReq stream
// proxyReq.write(body);
// proxyReq.end();
// }
// }
// }
// ],

],
// ],
// proxyTable: {
// '/api': { target: 'https://nuxt-auth-routes.glitch.me/', ws: false }
// },
Expand All @@ -61,20 +61,20 @@ module.exports = {
** 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 }
// }),
// // Api middleware
// // We add /api/login & /api/logout routes
// '~/api'
// ],
serverMiddleware: [
// body-parser middleware
bodyParser.json(),
// session middleware
session({
secret: 'super-secret-key',
resave: false,
saveUninitialized: false,
cookie: { maxAge: 60000 }
}),
// Api middleware
// We add /api/login & /api/logout routes
'~/api/index.js'
],
/*
** Headers of the page
*/
Expand Down
57 changes: 53 additions & 4 deletions package-lock.json

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

6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
"author": "wz",
"private": true,
"scripts": {
"dev": "cross-env BASE_URL='https://postman-echo.com' nuxt",
"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",
"generate": "nuxt generate",
Expand All @@ -26,6 +27,9 @@
"@nuxtjs/proxy": "^1.2.4",
"axios": "^0.18.0",
"babel-eslint": "^8.2.1",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"body-parser": "^1.18.3",
"cheerio": "^1.0.0-rc.2",
"cors": "^2.8.4",
Expand Down
33 changes: 33 additions & 0 deletions public/api/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@

import express from 'express';
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();
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: req.body.username };
return res.json({ username: req.body.password });
}
res.status(401).json({ message: "Bad credentials" });
});

router.post('/logout', (req, res) => {
delete req.session.authUser;
res.json({ ok: true });
});
//Export the server middleware
export default {
path: '/api',
handler: router
};
4 changes: 1 addition & 3 deletions public/middleware/authenticated.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
export default function ({ store, redirect }) {
// console.log(store);
// console.log(store.state);
if (!store.state.authenticated) {
if (!store.state.authUser) {
return redirect('/login');
}
}
11 changes: 9 additions & 2 deletions public/pages/login.vue
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
<template>
<div class="mylogin">
login page
<div class="container">
<form @submit.prevent="login">
<form @submit.prevent="login" v-if="!$store.state.authUser">
<p class="error" v-if="formError">{{formError}}</p>
<p>
<i>
Expand All @@ -15,6 +14,13 @@
<p>password: <input v-model="formPassword" type="password" name="password"></p>
<button type="submit">Login</button>
</form>
<div v-else>
Hello, {{$store.state.authUser && $store.state.authUser.username}} ,
<pre>I am the secret content, I am shown only when the use is connected.</pre>
<p>
<i>You can also refresh this page, you'll still be connected!</i>
</p>
</div>
</div>
</div>
</template>
Expand All @@ -35,6 +41,7 @@ export default {
password: this.formPassword
});
} catch (e) {
console.log('e', e);
this.formError = e.message;
}
}
Expand Down
9 changes: 8 additions & 1 deletion public/store/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,15 @@ const store = () => {
}
},
actions: {
// nuxtServerInit is called by Nuxt.js before server-rendering every page
nuxtServerInit({ commit }, { req }) {
console.log(req.session, req.session.authUser);
if (req.session && req.session.authUser) {
commit('SET_USER', req.session.authUser)
}
},
async login({ commit }, { username, password }) {
const { data } = await axios.post('/api/login', { username, password });
const { data } = await axios.post('/api/login', { username, password });
console.log(data);
commit('SET_USER', data);
}
Expand Down

0 comments on commit 4df1342

Please sign in to comment.