阅读 3376

vue+ egg 仿缤客网

图片

前言

这个项目是仿制缤客网的页面,因为缤客网机票页面打不开,所以就没有编写机票页面,并且后端的api我只写了booking页面、login页面、register页面,不足之处请见谅。

技术栈

前端:vue + stylus + axios

后端:egg.js + mysql + sequelize

部署:nginx + xshell + Xftp

效果演示

Vue前端

utils文件夹的路由封装

axios请求的封装

import axios from 'axios'

const host = 'http://127.0.0.1:7001/api'
export { host }

function request (url, method, data, header = {}) {
  return new Promise((resolve, reject) => {
    return axios({
      method: method,
      url: host + url,
      data: data,
      header: {
        'content-type': 'application/json' // 默认值
      }
    }).then((res) => {
      resolve(res.data)
    }).catch(error => {
      reject(error)
    })
  })
}

export function get (url, data) {
  return request(url, 'GET', data)
}

export function post (url, data) {
  return request(url, 'POST', data)
}

复制代码

router.js

路由的懒加载

import Vue from 'vue'
import Router from 'vue-router'

const _import_ = file => () => import(`@/pages/${file}.vue`)

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      redirect: '/booking'
    },
    {
      path: '/booking',
      name: 'booking',
      component: _import_('booking'),
      children: [
        {
          path: '/',
          name: '/',
          component: _import_('hotel'),
          meta: {
            title: 'Booking.com | 官网 | 热门酒店和民宿'
          }
        },
        {
          path: 'plane',
          name: 'plane',
          component: _import_('plane'),
          meta: {
            title: 'Booking 飞机'
          }
        },
        {
          path: 'rentCar',
          name: 'rentCar',
          component: _import_('rentCar'),
          meta: {
            title: 'Booking 租车'
          }
        },
        {
          path: 'fWheel',
          name: 'fWheel',
          component: _import_('fWheel'),
          meta: {
            title: 'Booking 观光和活动'
          }
        },
        {
          path: 'taxi',
          name: 'taxi',
          component: _import_('taxi'),
          meta: {
            title: 'Booking 出租车'
          }
        }
      ]
    },
    {
      path: '/user/login',
      name: 'login',
      component: _import_('login'),
      meta: {
        title: '登录'
      }
    },
    {
      path: '/user/register',
      name: 'register',
      component: _import_('register'),
      meta: {
        title: '注册'
      }
    }
  ]
})

复制代码

页面的编写

剩下的就是页面的编写了,下面请看后端

后端

页面结构

后端

sequelize的创建

  • 安装sequelize 这个可以去查资料
  • 在config的config.default.js文件加入一下代码
config.sequelize = {
    dialect:'mysql',
    host:'127.0.0.1',
    port: 3306,
    username: 'root',
    password: '******',
    database: 'booking'
  }
复制代码
  • 在config的plugin.js文件加入一下代码
// Sequelize插件
  sequelize: {
    enable:true,
    package:'egg-sequelize'
  }
复制代码
  • 在app同级目录下创建.sequelizer文件编写以下代码
'use strict'

const path = require('path');

module.exports = {
  config: path.join(__dirname, 'database/config.json'),
  'migrations-path': path.join(__dirname, 'database/migrations'),
  'seeders-path': path.join(__dirname, 'database/seeders'),
  'models-path': path.join(__dirname, 'app/model')
}
复制代码

执行 sequelize init 命令

./node_modules/.bin/sequelize init
复制代码

最后就是sequelize命令的使用 创建表,加入种子数据 sequelize上面不会的也可以看看

跨域问题

在config的config.default.js文件加入一下代码

config.security = {
    csrf: {
      enable: false,
      ignoreJSON: true
    },
    domainWhiteList: ['*']
  };
  
  config.cors = {
    origin: '*',
    allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'
  };
复制代码
  • 在config的plugin.js文件加入一下代码
cors: {
	  enable: true,
	  package: 'egg-cors'
  },
复制代码

mysql的链接

  • 安装MySQL
  • 在app的同级目录创建database文件config.js
{
  "development": {
    "username": "root",
    "password": "******",
    "database": "booking",
    "host": "127.0.0.1",
    "dialect": "mysql",
    "operatorsAliases": false
  },
  "test": {
    "username": "root",
    "password": "******",
    "database": "booking",
    "host": "127.0.0.1",
    "dialect": "mysql",
    "operatorsAliases": false
  },
  "production": {
    "username": "root",
    "password": "******",
    "database": "booking",
    "host": "127.0.0.1",
    "dialect": "mysql",
    "operatorsAliases": false
  }
}

复制代码

后端api的编写

router.js

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.prefix('/api')
  router.get('/booking/currency', controller.booking.getCurrency);
  router.get('/booking/location', controller.booking.getLocation);
  router.get('/booking/hotelType', controller.booking.getHotelType);
  router.get('/booking/hotelRent', controller.booking.getHotelRent);
  router.get('/booking/hotelStation', controller.booking.getHotelStation);
  router.post('/user/login', controller.user.login)
  router.post('/user/register', controller.user.register)
};
复制代码

controller层

'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
  async login() {
    const { ctx } = this;
    const { username, password } = ctx.request.body
    await ctx.service.user.loginIn({ username, password })
  }

  async register() {
    const { ctx } = this;
    const { username, password } = ctx.request.body
    await ctx.service.user.register({ username, password })
  }
}

module.exports = UserController;
复制代码

service层

const Service = require('egg').Service

class UserService extends Service {
  async loginIn(user) {
    // sql 及存储业务的组织
    const { ctx, app } = this
    const userInfo = await ctx.model.User.findOne({where: { username: user.username }})
    console.log(userInfo)
    let msg = ''
    let code = 0
    if (userInfo == null) {
      msg = '用户不存在,请注册'
      code = 378
    } else {
      if (user.password != userInfo.password) {
        msg = '密码错误,请重新输入'
        code = 399
      } else {
        msg = '登录成功'
        code = 200
      }
    }
    ctx.body = {
      msg: msg,
      code: code
    }
  }

  async register(user) {
    // sql 及存储业务的组织
    const { ctx, app } = this
    let msg = ''
    let code = 0
    const userInfo = await ctx.model.User.findOne({where: { username: user.username }})
    if (userInfo != null) {
      msg = '用户已存在,请重新注册'
      code = 356
    } else {
      await ctx.model.User.create(user)
      msg = '注册成功'
      code = 200
    }
    ctx.body = {
      msg: msg,
      code: code
    }
  }
}

module.exports = UserService
复制代码

model层

module.exports = app => {
  // console.log('model层')
  const { INTEGER, STRING, BOOLEAN }  = app.Sequelize;
  const user = app.model.define('user', {
    id: {
      allowNull: false,// 允许为空吗
      primaryKey: true,// 主键
      autoIncrement: true,// 自增
      type: INTEGER,// 类型
      comment: '用户id'
    },
    username: {
      type: STRING(50),
      primaryKey: true,// 主键
      allowNull: false,
      defaultValue: '',
      comment: '用户名'
    },
    password: {
      type: STRING(32),
      allowNull: false,
      defaultValue: '',
      comment: '用户密码'
    },
    disabled: {
      type: BOOLEAN,
      allowNull: false,
      defaultValue: false,
      comment: '是否是禁用状态'
    }
  },
  {
    timestamps: false,
    tableName: 'user',
    underscored: false
  })
  // console.log(location, '-----')
  return user
}
复制代码

后端差不多了 最后是网站的上线

网站的部署

网站的部署看这里

nginx服务器搭建以及配置

egg.js部署到服务器

nginx与mysql安装

nginx与mysql安装

Nginx配置文件详细说明

非常感谢以上的文档

我的github地址: 我的github

网站地址: 网站地址

最后

最后的最后当然是厚着脸皮的再求个 star 啦,如果觉得我的项目还不错的话,就给个 star 鼓励一下吧~