1. Project construction
"scripts": {
"start": "node app.js"."server": "nodemon app.js"
}
// NPM run server ensures real-time project updates
Copy the code
2, app. Js
`
const koa = require("koa");
const Router = require("koa-router");
const bodyParser = require("koa-bodyparser");
const mongoose = require("mongoose");
const passport = require("koa-passport");
const db = require("./config/keys").mongoURL;
/ / instantiate
const app = new koa();
const router = new Router();
app.use(bodyParser());
/ / routing
router.get("/".async (ctx) => {
ctx.body = { msg: "Hello Koa Interfaces!" };
});
/ / the connection
mongoose
.connect(db, { useNewUrlParser: true.useUnifiedTopology: true })
.then(() = > {
console.log("1111 connected");
})
.catch((err) = > {
console.log(err, "sssssss");
});
/ / introduction of the users, js
const users = require("./routes/api/user");
const profile = require("./routes/api/profile");
// Configure the routing address
router.use("/api/users", users);
router.use("/api/profile", profile);
/ / token
app.use(passport.initialize());
app.use(passport.session());
/// callback to the config file passport. Js
require('./config/passport')(passport);
// Configure the route
app.use(router.routes()).use(router.allowedMethods());
const port = process.env.PORT || 10086;
app.listen(port, () = > {
console.log(`server started on ${port}`);
});
Copy the code
`
3. A series of plug-ins used
- mongoose
- Database connection
- Mongoose’s Schema and Mongoose. Model (‘Schema’, Schema);
- Address: www.mongoosejs.net/docs/guide….
- passport-jwt
- Tooken parsing
const { secretOrKey } = require(".. /config/keys"); const JwtStrategy = require("passport-jwt").Strategy; const ExtractJwt = require("passport-jwt").ExtractJwt; const opts = {}; opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken(); opts.secretOrKey = secretOrKey; const mongoose = require("mongoose"); // const User = mongoose.model('users'); module.exports = (passport) => { passport.use( new JwtStrategy(opts, async (jwt_payload, done) => { console.log(jwt_payload, "jwt_payload"); console.log(User, "User"); const user = await User.findById(jwt_payload.id); if (user) { return done(null, user); } else { return done(null, false); }})); };Copy the code
- Address: www.npmjs.com/package/koa…
- koa-passport
- Verify that the token is valid
router.get( "/current", passport.authenticate("jwt", { session: false }), async (ctx) => { const { email, id, name, avatar } = ctx.state.user; ctx.body = { email, id, name, avatar }; });Copy the code
- Address: www.npmjs.com/package/koa…
- koa-router
- Dividing interface paths (Interface Addresses)
- bcrypt
- Password encryption
const bcrypt = require("bcrypt"); const tools = { enbcrypt(password) { const salt = bcrypt.genSaltSync(10); const hash = bcrypt.hashSync(password, salt); return hash; }}; module.exports = tools;Copy the code
- Address: www.npmjs.com/package/bcr…
- jsonwebtoken
- To generate the token
// expiresIn expiration time (s) const token = jwt.sign(payload, secretOrKey, {expiresIn: 3600});Copy the code
- Address: www.npmjs.com/package/jso…
- koa-bodyparser
- To process the POST request parameters
- Address: www.npmjs.com/package/koa…
- validator
- Data validation
const Validator = require("validator"); module.exports = function validateLoginInput(data) { let errors = {}; if (! Validator.islength (data.password, {min: 6, Max: 18})) {errors.name = "Password length should not be less than 6 and not more than 18 characters "; } return { errors, isValid: isEmpty(errors), }; };Copy the code
- Address: www.npmjs.com/package/val…