Express+Vue+MongoDB

作者: Franchen | 来源:发表于2017-04-14 11:31 被阅读192次

    环境搭建

    • 首先要安装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
    效果预览

    相关文章

      网友评论

      • balefulScript:难道不应该搭建express 环境,然后在vue-cli 吗,感觉本末倒置了

      本文标题:Express+Vue+MongoDB

      本文链接:https://www.haomeiwen.com/subject/ykhwattx.html