npm install汇总 逃离我推掉我的手 2021-10-06 03:14 287阅读 0赞 ### npm install 汇总持续更新 ### * Web应用框架\_express * 数据库\_mongoose * Post请求body解析\_body-parser * 加密插件\_bcrypt * 个人头像\_gravatar * jwt\_jsonwebtoken * 热开发\_nodemon * 实现多开\_concurrently * 异步请求\_axios * vue存储用户信息\_vuex 检索:https://www.npmjs.com/ # Web应用框架\_express # Express 是一个简洁而灵活的 node.js Web应用框架, 提供了一系列强大特性帮助你创建各种 Web 应用,和丰富的 HTTP 工具。 使用 Express 可以快速地搭建一个完整功能的网站。 Express 框架核心特性: 可以设置中间件来响应 HTTP 请求。 定义了路由表用于执行不同的 HTTP 请求动作。 可以通过向模板传递参数来动态渲染 HTML 页面。 在main.js中添加 cnpm install express const express = require("express");//引入web应用框架 const app = express(); //默认访问根路径 app.get("/",(req,res)=>{ res.send("Hello World ..."); }) //定义应用端口 const port = process.env.PORT || 5000; //监听服务是否启动 app.listen(port,()=>{ console.log(`Server running on port ${port}`); }) # 数据库\_mongoose # cnpm install mongoose const mongoose = require("mongoose");//引入mongodb //mongodb配置 const db = require("./config/base").mongodbURI; mongoose.connect(db) .then(()=>console.log("Mongodb connected ...")) .catch(error=>console.log(error)); # Post请求body解析\_body-parser # cnpm install body-parser const bodyParser = require("body-parser");//引入body解析 //使用body-parser中间件 app.use(bodyParser.urlencoded({extended:false})); app.use(bodyParser.json()); # 加密插件\_bcrypt # npm install bcrypt const bcrypt = require("bcrypt"); //引入加密中间件 bcrypt.genSalt(10, function(err, salt) { bcrypt.hash(newUser.password, salt, (err, hash) => { if (err) throw err; newUser.password = hash; newUser.save() .then(user=>res.json(user)) .catch(error =>console.log(error)); }); }); //密码校验 bcrpt.compare(password,user.password) .then(res=>{ if (res){ res.json({msg:"success"}) } else{ return res.status(400).json({data:"密码错误..."}); } }) # 个人头像\_gravatar # cnpm i gravatar const gravatar = require("gravatar"); const avatar = gravatar.url(req.body.email,{s:'200',r:'pg',d:'mm'});//返回默认头像 官方网站:https://en.gravatar.com/ 网站通过个人邮箱注册并创建个人头像 # jwt\_jsonwebtoken # cnpm install jsonwebtoken const jwt = require("jsonwebtoken"); //引入jwt const rule = {id:user.id,name:user.name}; jwt.sign(rule,base.token,{expiresIn:3600},(error,token)=>{ if (error) throw error; res.json({ success:true, token:"Bearer "+token }); }) jwt认证配置 cnpm install passport-jwt passport 在main.js中配置 const passport = require("passport"); //passport 初始化 app.use(passport.initialize()); require("./config/passport")(passport); //将passport对象传入passport.js 创建passport.js中配置 const JwtStrategy = require('passport-jwt').Strategy; const ExtractJwt = require('passport-jwt').ExtractJwt; const mongoose = require("mongoose"); const User = mongoose.model("users"); const base = require("../config/base"); const opts = {} //header Authorization:Bearer ... opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken(); opts.secretOrKey = base.secretOrKey; //passport对象 module.exports = passport =>{ //校验请求header中的token passport.use(new JwtStrategy(opts, function(jwt_payload, done) { //获取token中基本数据 id name console.log(jwt_payload); //获取token解析的参数,通过id在数据库中查询,将user对象放到request中 User.findById(jwt_payload.id) .then(user=>{ if (user){ return done(null,user); } return done(null,false); }) .catch(error=>console.log(error)); })) } 配置接口 /** * $route GET api/users/authtest * @desc 校验请求 测试 * @auth private */ router.get("/auth",passport.authenticate("jwt",{session:false}),(req,res)=>{ res.json({ id:req.user.id, name:req.user.name, email:req.user.email, identity:req.user.identity }); }) jwt-token解码 npm install jwt-decode import jwt_decode from "jwt-decode"; // 解析token const user = jwt_decode(token); # 热开发\_nodemon # nodemon自动重新加载。nodemon是一个实用程序,它将监视源中的任何更改并自动重新启动服务器。 安装 cnpm install nodemon -g 使用 nodemon server.js # 实现多开\_concurrently # 安装 cnpm install concurrently 使用示例 "dev": "concurrently \"npm run serve1\" \"npm run serve2\"" # 异步请求\_axios # cnpm install axios //请求拦截 axios.interceptors.request.use(req=>{ startLoading(); //接口请求前,将本地存储的token放到header中 if (localStorage.eleToken){ req.headers.Authorization = localStorage.eleToken; } return req; },error => { return Promise.reject(error); }); //响应拦截 axios.interceptors.response.use(res=>{ stopLoading(); return res; },error => { stopLoading(); Message.error(error); // 401 token过期处理 const { status } = error.response if (status == 401) { Message.error('token值无效,请重新登录') // 清除token localStorage.removeItem('eleToken') // 跳转登录 router.push('/login') } return Promise.reject(error); }); # vue存储用户信息\_vuex # cnpm install vuex src/store.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const types = { SET_IS_AUTNENTIATED: 'SET_IS_AUTNENTIATED', // 是否认证通过 SET_USER: 'SET_USER' // 用户信息 } const state = { // 需要维护的状态 isAutnenticated: false, // 是否认证 user: {} // 存储用户信息 } const getters = { isAutnenticated: state => state.isAutnenticated, user: state => state.user } const mutations = { [types.SET_IS_AUTNENTIATED](state, isAutnenticated) { if (isAutnenticated) state.isAutnenticated = isAutnenticated else state.isAutnenticated = false }, [types.SET_USER](state, user) { if (user) state.user = user else state.user = {} } } const actions = { setIsAutnenticated: ({ commit }, isAutnenticated) => { commit(types.SET_IS_AUTNENTIATED, isAutnenticated) }, setUser: ({ commit }, user) => { commit(types.SET_USER, user) }, clearCurrentState: ({ commit }) => { commit(types.SET_IS_AUTNENTIATED, false) commit(types.SET_USER, null) } } export default new Vuex.Store({ state, getters, mutations, actions }) src/App.vue <template> <div id="app"> <router-view/> </div> </template> <script> import jwt_decode from "jwt-decode"; export default { name: "app", created() { //在本地存储获取token if (localStorage.eleToken) { //解析token const decode = jwt_decode(localStorage.eleToken); //存储 this.$store.dispatch("setIsAutnenticated", !this.isEmpty(decode)); this.$store.dispatch("setUser", decode); } }, methods: { isEmpty(value) { return ( value === undefined || value === null || (typeof value === "object" && Object.keys(value).length === 0) || (typeof value === "string" && value.trim().length === 0) ); } } }; </script> <style> html,body,#app { width: 100%; height: 100%; } </style>
还没有评论,来说两句吧...