Express+Vue+MongoDB

环境搭建

  • 首先要安装vue-cliexpress-generator
$ npm install vue-cli -g
$ npm install express-generator -g
  • 使用手脚架搭建vue环境和express环境
# pwd /var/http/
$ vue init webpack project1
$ cd project1
$ npm install
# pwd /var/http/project1/
$ express server
$ cd server
$ npm install
  • 添加MongoDB驱动。MongoDB的安装非本文重点,请自行Google方法或见win10安装MongoDB
# pwd /var/http/project1/server/
$ npm install mongodb --save
$ npm install mongoose --save
  • 以上我们完成了基本环境的搭建,如图
基本架构

细节调整

我们想要的效果是,Vue编译后直接放在server的public里面,然后运行Express后可以直接访问。

  • 首先修改Vue编译后的存放地址
# 进入config/index.js文件,修改index和assetsRoot的地址
...
index: path.resolve(__dirname, '../server/public/index.html'),
assetsRoot: path.resolve(__dirname, '../server/public'),
...
  • 修改package.json的script命令
# 进入package.json,添加server命令
...
"scripts": {
    "dev": "node build/dev-server.js",
    "server": "node server/bin/www",
    "build": "node build/build.js",
    "unit": "cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run",
    "e2e": "node test/e2e/runner.js",
    "test": "npm run unit && npm run e2e",
    "lint": "eslint --ext .js,.vue src test/unit/specs test/e2e/specs"
  },
...
  • 添加favicon.ico和修改express的index路由
# 将favicon.ico文件放入server/public文件夹下
# 进入server/app.js,将app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))前的注释去掉
# 进入server/routes/index.js,按如下修改
router.get('/', function(req, res, next) {
    // res.render('index', { title: 'Express' });
    res.redirect('/public/index.html');
});

测试运行

  • 编译Vue代码
# pwd /var/http/project1/
$ npm run build
  • 运行express服务器
# pwd /var/http/poject1/
$ npm run server
  • 浏览器打开http://localhost:3000
效果预览
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容