1.安装 nodejs
2.安装 git
3.下载 vue-element-admin
安装本地mongodb或者在mongodb官网新建免费的云端服务器
建议
本项目的定位是后台集成方案,不太适合当基础模板来进行二次开发。因为本项目集成了很多你可能用不到的功能,会造成不少的代码冗余。如果你的项目不关注这方面的问题,也可以直接基于它进行二次开发。
- 集成方案: vue-element-admin
- 基础模板: vue-admin-template
- 桌面终端: electron-vue-admin
- Typescript 版: vue-typescript-admin-template (鸣谢: @Armour)
- Others: awesome-project
安装git
root@lin-2 ~ # git
usage: git [--version] [--help] [-C ] [-c =]
[--exec-path[=]] [--html-path] [--man-path] [--info-path]
[-p | --paginate | -P | --no-pager] [--no-replace-objects] [--bare]
[--git-dir=] [--work-tree=] [--namespace=]
[]
These are common Git commands used in various situations:
start a working area (see also: git help tutorial)
clone Clone a repository into a new directory
init Create an empty Git repository or reinitialize an existing one
work on the current change (see also: git help everyday)
add Add file contents to the index
mv Move or rename a file, a directory, or a symlink
restore Restore working tree files
rm Remove files from the working tree and from the index
examine the history and state (see also: git help revisions)
bisect Use binary search to find the commit that introduced a bug
diff Show changes between commits, commit and working tree, etc
grep Print lines matching a pattern
log Show commit logs
show Show various types of objects
status Show the working tree status
grow, mark and tweak your common history
branch List, create, or delete branches
commit Record changes to the repository
merge Join two or more development histories together
rebase Reapply commits on top of another base tip
reset Reset current HEAD to the specified state
switch Switch branches
tag Create, list, delete or verify a tag object signed with GPG
collaborate (see also: git help workflows)
fetch Download objects and refs from another repository
pull Fetch from and integrate with another repository or a local branch
push Update remote refs along with associated objects
'git help -a' and 'git help -g' list available subcommands and some
concept guides. See 'git help ' or 'git help '
to read about a specific subcommand or concept.
See 'git help git' for an overview of the system.
root@lin-2 ~ #
安装vue-admin
root@lin-2 Desktop # git clone https://github.com/PanJiaChen/vue-admin-template.git
Cloning into 'vue-admin-template'...
remote: Enumerating objects: 2177, done.
remote: Total 2177 (delta 0), reused 0 (delta 0), pack-reused 2177
Receiving objects: 100% (2177/2177), 1012.93 KiB | 65.00 KiB/s, done.
Resolving deltas: 100% (1161/1161), done.
安装node
root@lin-2 Desktop # npm install
npm WARN saveError ENOENT: no such file or directory, open '/private/var/root/Desktop/package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open '/private/var/root/Desktop/package.json'
npm WARN Desktop No description
npm WARN Desktop No repository field.
npm WARN Desktop No README data
npm WARN Desktop No license field.
up to date in 1.061s
found 0 vulnerabilities
root@lin-2 Desktop # cd vue
cd: no such file or directory: vue
root@lin-2 Desktop # cd vue-admin-template
root@lin-2 vue-admin-template # npm install
npm WARN deprecated [email protected]: This loader has been deprecated. Please use eslint-webpack-plugin
npm WARN deprecated @hapi/[email protected]: Switch to 'npm install joi'
npm WARN deprecated [email protected]: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated [email protected]: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
npm WARN deprecated @hapi/[email protected]: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated @hapi/[email protected]: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated @hapi/[email protected]: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated @hapi/[email protected]: Moved to 'npm install @sideway/address'
npm WARN deprecated [email protected]: this library is no longer supported
npm WARN deprecated [email protected]: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
npm WARN deprecated [email protected]: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
npm WARN deprecated [email protected]: request-promise-native has been deprecated because it extends the now deprecated request package, see https://github.com/request/request/issues/3142
npm WARN deprecated [email protected]: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated [email protected]: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated [email protected]: use String.prototype.padStart()
> [email protected] install /private/var/root/Desktop/vue-admin-template/node_modules/jest-haste-map/node_modules/fsevents
> node install.js
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.
No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'.
No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.
gyp: No Xcode or CLT version detected!
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:351:16)
gyp ERR! stack at ChildProcess.emit (events.js:314:20)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:276:12)
gyp ERR! System Darwin 20.1.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /private/var/root/Desktop/vue-admin-template/node_modules/jest-haste-map/node_modules/fsevents
gyp ERR! node -v v14.11.0
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok
> [email protected] install /private/var/root/Desktop/vue-admin-template/node_modules/deasync
> node ./build.js
`darwin-x64-node-14` exists; testing
Binary is fine; exiting
> [email protected] install /private/var/root/Desktop/vue-admin-template/node_modules/watchpack-chokidar2/node_modules/fsevents
> node install.js
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.
No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'.
No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.
gyp: No Xcode or CLT version detected!
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:351:16)
gyp ERR! stack at ChildProcess.emit (events.js:314:20)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:276:12)
gyp ERR! System Darwin 20.1.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /private/var/root/Desktop/vue-admin-template/node_modules/watchpack-chokidar2/node_modules/fsevents
gyp ERR! node -v v14.11.0
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok
> [email protected] install /private/var/root/Desktop/vue-admin-template/node_modules/webpack-dev-server/node_modules/fsevents
> node install.js
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.
No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'.
No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.
gyp: No Xcode or CLT version detected!
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:351:16)
gyp ERR! stack at ChildProcess.emit (events.js:314:20)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:276:12)
gyp ERR! System Darwin 20.1.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /private/var/root/Desktop/vue-admin-template/node_modules/webpack-dev-server/node_modules/fsevents
gyp ERR! node -v v14.11.0
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok
> [email protected] install /private/var/root/Desktop/vue-admin-template/node_modules/yorkie
> node bin/install.js
setting up Git hooks
done
> [email protected] postinstall /private/var/root/Desktop/vue-admin-template/node_modules/babel-runtime/node_modules/core-js
> node -e "try{require('./postinstall')}catch(e){}"
Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!
The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock
Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)
> [email protected] postinstall /private/var/root/Desktop/vue-admin-template/node_modules/core-js
> node -e "try{require('./postinstall')}catch(e){}"
Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!
The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock
Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)
> [email protected] postinstall /private/var/root/Desktop/vue-admin-template/node_modules/ejs
> node ./postinstall.js
Thank you for installing EJS: built with the Jake JavaScript build tool (https://jakejs.com/)
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN [email protected] No repository field.
added 1706 packages from 1167 contributors and audited 1710 packages in 94.6s
69 packages are looking for funding
run `npm fund` for details
found 6 vulnerabilities (4 low, 2 high)
run `npm audit fix` to fix them, or `npm audit` for details
root@lin-2 vue-admin-template # npm run dev
> [email protected] dev /private/var/root/Desktop/vue-admin-template
> vue-cli-service serve
INFO Starting development server...
98% after emitting CopyPlugin
DONE Compiled successfully in 17645ms 上午10:35:26
App running at:
- Local: http://localhost:9529/
- Network: http://10.248.82.249:9529/
Note that the development build is not optimized.
To create a production build, run npm run build.
request invoke:/dev-api/vue-admin-template/user/info
WAIT Compiling... 上午10:36:25
98% after emitting CopyPlugin
WARNING Compiled with 1 warning 上午10:36:26
Module Warning (from ./node_modules/eslint-loader/index.js):
/private/var/root/Desktop/vue-admin-template/src/router/index.js
75:22 error Newline required at end of file but not found eol-last
✖ 1 problem (1 error, 0 warnings)
1 error and 0 warnings potentially fixable with the `--fix` option.
You may use special comments to disable some warnings.
Use // eslint-disable-next-line to ignore the next line.
Use /* eslint-disable */ to ignore all warnings in a file.
App running at:
- Local: http://localhost:9529/
- Network: http://10.248.82.249:9529/
删除多余界面 router/index
删除后的界面如下
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
/* Layout */
import Layout from '@/layout'
/**
* Note: sub-menu only appear when route children.length >= 1
* Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
*
* hidden: true if set true, item will not show in the sidebar(default is false)
* alwaysShow: true if set true, will always show the root menu
* if not set alwaysShow, when item has more than one children route,
* it will becomes nested mode, otherwise not show the root menu
* redirect: noRedirect if set noRedirect will no redirect in the breadcrumb
* name:'router-name' the name is used by (must set!!!)
* meta : {
roles: ['admin','editor'] control the page roles (you can set multiple roles)
title: 'title' the name show in sidebar and breadcrumb (recommend set)
icon: 'svg-name' the icon show in the sidebar
breadcrumb: false if set false, the item will hidden in breadcrumb(default is true)
activeMenu: '/example/list' if set path, the sidebar will highlight the path you set
}
*/
/**
* constantRoutes
* a base page that does not have permission requirements
* all roles can be accessed
*/
export const constantRoutes = [
{
path: '/login',
component: () => import('@/views/login/index'),
hidden: true
},
{
path: '/404',
component: () => import('@/views/404'),
hidden: true
},
{
path: '/',
component: Layout,
redirect: '/dashboard',
children: [{
path: 'dashboard',
name: 'Dashboard',
component: () => import('@/views/dashboard/index'),
meta: { title: 'Dashboard', icon: 'dashboard' }
}]
},
// 404 page must be placed at the end !!!
{ path: '*', redirect: '/404', hidden: true }
]
const createRouter = () => new Router({
// mode: 'history', // require service support
scrollBehavior: () => ({ y: 0 }),
routes: constantRoutes
})
const router = createRouter()
// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
const newRouter = createRouter()
router.matcher = newRouter.matcher // reset router
}
export default router
安装es6-promise
root@lin-2 vue-admin-template # cnpm install --save es6-promise
✔ Installed 1 packages
✔ Linked 0 latest versions
✔ Run 0 scripts
✔ All packages installed (1 packages installed from npm registry, used 235ms(network 234ms), speed 15.85kB/s, json 1(3.71kB), tarball 0B)
root@lin-2 vue-admin-template #
安装老师Axios 插件
http.js
import Vue from 'vue';
import Axios from 'axios';
import {Promise} from 'es6-promise';
import {MessageBox, Message} from 'element-ui'
Axios.defaults.timeout = 30000; // 1分钟
Axios.defaults.baseURL = '';
Axios.interceptors.request.use(function (config) {
// Do something before request is sent
//change method for get
/*if(process.env.NODE_ENV == 'development'){
config['method'] = 'GET';
console.log(config)
}*/
if (config['MSG']) {
// Vue.prototype.$showLoading(config['MSG']);
} else {
// Vue.prototype.$showLoading();
}
// if(user.state.token){//用户登录时每次请求将token放入请求头中
// config.headers["token"] = user.state.token;
// }
if (config['Content-Type'] === 'application/x-www-form-urlencoded;') {//默认发application/json请求,如果application/x-www-form-urlencoded;需要使用transformRequest对参数进行处理
/*config['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';*/
config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
config['transformRequest'] = function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&")
};
}
//config.header['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
return config;
}, function (error) {
// Do something with request error
// Vue.$vux.loading.hide()
return Promise.reject(error);
});
Axios.interceptors.response.use(
response => {
// Vue.$vux.loading.hide();
return response.data;
},
error => {
// Vue.$vux.loading.hide();
if (error.response) {
switch (error.response.status) {
case 404:
Message({
message: '' || 'Error',
type: 'error',
duration: 5 * 1000
})
break;
default:
Message({
message: '' || 'Error',
type: 'error',
duration: 5 * 1000
})
}
} else if (error instanceof Error) {
console.error(error);
} else {
Message({
message: '' || 'Error',
type: 'error',
duration: 5 * 1000
})
}
return Promise.reject(error.response);
});
export default Vue.prototype.$http = Axios;
配置axios代理
'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')
function resolve(dir) {
return path.join(__dirname, dir)
}
const name = defaultSettings.title || 'vue Admin Template' // page title
// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following methods:
// port = 9528 npm run dev OR npm run dev --port = 9528
const port = process.env.port || process.env.npm_config_port || 9528 // dev port
// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
/**
* You will need to set publicPath if you plan to deploy your site under a sub path,
* for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
* then publicPath should be set to "/bar/".
* In most cases please use '/' !!!
* Detail: https://cli.vuejs.org/config/#publicpath
*/
publicPath: '/',
outputDir: 'dist',
assetsDir: 'static',
lintOnSave: process.env.NODE_ENV === 'development',
productionSourceMap: false,
devServer: {
port: port,
open: true,
overlay: {
warnings: false,
errors: true
},
proxy: {
// change xxx-api/login => mock/login
// detail: https://cli.vuejs.org/config/#devserver-proxy
[process.env.VUE_APP_BASE_API]: {
target: `http://127.0.0.1:${port}/mock`,
changeOrigin: true,
pathRewrite: {
['^' + process.env.VUE_APP_BASE_API]: ''
}
},
['/api']: {
target: `http://127.0.0.1:3000`,
changeOrigin: true,
pathRewrite: {
['^' + '/api']: ''
}
}
},
before: require('./mock/mock-server.js')
},
configureWebpack: {
// provide the app's title in webpack's name field, so that
// it can be accessed in index.html to inject the correct title.
name: name,
resolve: {
alias: {
'@': resolve('src')
}
}
},
chainWebpack(config) {
// it can improve the speed of the first screen, it is recommended to turn on preload
config.plugin('preload').tap(() => [
{
rel: 'preload',
// to ignore runtime.js
// https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
include: 'initial'
}
])
// when there are many pages, it will cause too many meaningless requests
config.plugins.delete('prefetch')
// set svg-sprite-loader
config.module
.rule('svg')
.exclude.add(resolve('src/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
config
.when(process.env.NODE_ENV !== 'development',
config => {
config
.plugin('ScriptExtHtmlWebpackPlugin')
.after('html')
.use('script-ext-html-webpack-plugin', [{
// `runtime` must same as runtimeChunk name. default is `runtime`
inline: /runtime\..*\.js$/
}])
.end()
config
.optimization.splitChunks({
chunks: 'all',
cacheGroups: {
libs: {
name: 'chunk-libs',
test: /[\\/]node_modules[\\/]/,
priority: 10,
chunks: 'initial' // only package third parties that are initially dependent
},
elementUI: {
name: 'chunk-elementUI', // split elementUI into a single package
priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
},
commons: {
name: 'chunk-commons',
test: resolve('src/components'), // can customize your rules
minChunks: 3, // minimum common number
priority: 5,
reuseExistingChunk: true
}
}
})
// https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
config.optimization.runtimeChunk('single')
}
)
}
}
main.js中加入http
import http from './utils/http'
Vue.use(http)
main.js
import Vue from 'vue'
import 'normalize.css/normalize.css' // A modern alternative to CSS resets
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import locale from 'element-ui/lib/locale/lang/en' // lang i18n
import '@/styles/index.scss' // global css
import App from './App'
import store from './store'
import router from './router'
import '@/icons' // icon
import '@/permission' // permission control
import http from './utils/http'
Vue.use(http)
/**
* If you don't want to use mock-server
* you want to use MockJs for mock api
* you can execute: mockXHR()
*
* Currently MockJs will be used in the production environment,
* please remove it before going online ! ! !
*/
if (process.env.NODE_ENV === 'production') {
const { mockXHR } = require('../mock')
mockXHR()
}
// set ElementUI lang to EN
Vue.use(ElementUI, { locale })
// 如果想要中文版 element-ui,按如下方式声明
// Vue.use(ElementUI)
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
调用接口:
index.vue
欢迎
全局安装koa-generator,执行下面命令
root@lin-2 ~ # cd Desktop/vue-admin-template
root@lin-2 vue-admin-template # cnpm install -g koa-generator
Downloading koa-generator to /usr/local/lib/node_modules/koa-generator_tmp
Copying /usr/local/lib/node_modules/koa-generator_tmp/[email protected]@koa-generator to /usr/local/lib/node_modules/koa-generator
Installing koa-generator's dependencies to /usr/local/lib/node_modules/koa-generator/node_modules
[1/3] [email protected] installed at node_modules/[email protected]@sorted-object
[2/3] [email protected] installed at node_modules/[email protected]@commander
[3/3] [email protected] installed at node_modules/[email protected]@mkdirp
deprecate [email protected] Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)
All packages installed (4 packages installed from npm registry, used 952ms(network 949ms), speed 43.94kB/s, json 4(11.26kB), tarball 30.44kB)
[[email protected]] link /usr/local/bin/koa@ -> /usr/local/lib/node_modules/koa-generator/bin/koa
[[email protected]] link /usr/local/bin/koa2@ -> /usr/local/lib/node_modules/koa-generator/bin/koa2
构建koa2项目代码如下
root@lin-2 vue-admin-template # koa2 projectName
create : projectName
create : projectName/package.json
create : projectName/app.js
create : projectName/routes
create : projectName/routes/index.js
create : projectName/routes/users.js
create : projectName/public
create : projectName/views
create : projectName/views/index.pug
create : projectName/views/layout.pug
create : projectName/views/error.pug
create : projectName/bin
create : projectName/bin/www
create : projectName/public/javascripts
create : projectName/public/stylesheets
create : projectName/public/stylesheets/style.css
install dependencies:
$ cd projectName && npm install
run the app:
$ DEBUG=projectName:* npm start
create : projectName/public/images
root@lin-2 vue-admin-template #
初始化后台项目插件,命令属下
root@lin-2 vue-admin-template # cd projectName
root@lin-2 projectName # npm install
npm WARN deprecated [email protected]: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
npm WARN deprecated [email protected]: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
npm WARN deprecated [email protected]: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated [email protected]: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated [email protected]: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
> [email protected] install /private/var/root/Desktop/vue-admin-template/projectName/node_modules/fsevents
> node install.js
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.
No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'.
No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.
gyp: No Xcode or CLT version detected!
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:351:16)
gyp ERR! stack at ChildProcess.emit (events.js:314:20)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:276:12)
gyp ERR! System Darwin 20.1.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /private/var/root/Desktop/vue-admin-template/projectName/node_modules/fsevents
gyp ERR! node -v v14.11.0
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok
> [email protected] postinstall /private/var/root/Desktop/vue-admin-template/projectName/node_modules/core-js
> node -e "try{require('./postinstall')}catch(e){}"
Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!
The project needs your help! Please consider supporting of core-js on Open Collective or Patreon:
> https://opencollective.com/core-js
> https://www.patreon.com/zloirock
Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)
> [email protected] postinstall /private/var/root/Desktop/vue-admin-template/projectName/node_modules/nodemon
> node bin/postinstall || exit 0
npm notice created a lockfile as package-lock.json. You should commit this file.
added 393 packages from 269 contributors and audited 394 packages in 20.934s
7 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
root@lin-2 projectName #
项目试运行
root@lin-2 projectName # npm run dev
root@lin-2 projectName # npm run dev
> [email protected] dev /private/var/root/Desktop/vue-admin-template/projectName
> nodemon bin/www
[nodemon] 1.19.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node bin/www`
注册mongoose
创建组织
创建项目
创建集群
创建共享集群
选择新加坡
添加数据库用户
添加网络访问
加载样本
在集群中的创建test数据库
安装mongoose
root@lin-2 projectName # npm install mongoose --save
+ [email protected]
added 24 packages from 93 contributors and audited 418 packages in 16.297s
9 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
root@lin-2 projectName #
创建db目录
config.js ↓
module.exports = {
// dbs: 'mongodb://139.159.253.110:27017/test1'
dbs: 'mongodb+srv://xxwozixin:<需要修改>@cluster0-7d5kk.mongodb.net/test?retryWrites=true&w=majority'
}
user.js ↓
const mongoose = require('mongoose')
const feld={
name: String,
age: Number,
//人物标签
labels:Number
}
//自动添加更新时间创建时间:
let personSchema = new mongoose.Schema(feld, {timestamps: {createdAt: 'created', updatedAt: 'updated'}})
module.exports= mongoose.model('User',personSchema)
修改app.js
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const index = require('./routes/index')
const users = require('./routes/users')
const mongoose = require('mongoose')
const dbconfig = require('./db/config')
mongoose.connect(dbconfig.dbs, {useNewUrlParser: true,useUnifiedTopology: true})
const db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('mongoose 连接成功')
});
// error handler
onerror(app)
// middlewares
app.use(bodyparser({
enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))
app.use(views(__dirname + '/views', {
extension: 'pug'
}))
// logger
app.use(async (ctx, next) => {
const start = new Date()
await next()
const ms = new Date() - start
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
// error-handling
app.on('error', (err, ctx) => {
console.error('server error', err, ctx)
});
module.exports = app
// error handler
onerror(app)
// middlewares
app.use(bodyparser({
enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))
app.use(views(__dirname + '/views', {
extension: 'pug'
}))
// logger
app.use(async (ctx, next) => {
const start = new Date()
await next()
const ms = new Date() - start
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
// error-handling
app.on('error', (err, ctx) => {
console.error('server error', err, ctx)
});
module.exports = app
配置router下的users.js
users.js的配置
const router = require('koa-router')()
const User = require('../db/models/user')
router.prefix('/users')
router.get('/add', function (ctx, next) {
ctx.body = 'this is a users/bar response'
})
router.get('/', function (ctx, next) {
ctx.body = 'this is a users response!'
})
router.get('/bar', function (ctx, next) {
ctx.body = 'this is a users/bar response'
})
module.exports = router
npm run dev 跑起项目
root@lin-2 projectName # npm run dev
> [email protected] dev /private/var/root/Desktop/vue-admin-template/projectName
> nodemon bin/www
[nodemon] 1.19.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node bin/www`
mongoose 连接成功