前后端连接

前言

构建一个校园管理项目,用mongodb作为后台数据库,koa2创建一个服务端应用程序项目,用vue-admin-template构建一个管理项目,个人计算机既可以作为服务器也可以作为客户端。
这篇文章主要讲解客户端如何与服务端连接。

服务端与数据库连接教程

一、配置客户端

在这里插入图片描述
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;

在vue.config.js配置axios代理实现跨域请求

项目开发是使用vue-cli脚手架创建的项目,可以直接利用Node.js代理服务器,通过修改vue.config.js配置文件中devServer配置项中的proxy实现跨域请求。
为什么要实现跨域请求?因为浏览器不允许跨域访问。要从localhost:9528端口访问localhost:3000端口就是跨域访问。
这个代理配置把http:localhost:9528/xxx的请求转到localhost:3000的接口去就不算跨域了。

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']: {     // 拦截以/api开头的接口地址
        target: `http://localhost:3000`,   // 要跨域的域名
        changeOrigin: true,  // 是否跨域,设置成true:发送请求头中host会设置成target,false则为host
        pathRewrite: {
          ['^' + '/api']: ''
          // 本身接口中没有api这种通用前缀,所以要rewrite,如果本身有则去掉
          //  //使用'^/api':' '   可以把接口中的虚拟/api去掉。
          // 使用/api和'^/api':' '的作用:既能拥有正确的跨域标识,又能在请求接口的时候去掉/api。
        }
      }

跨域请求后请求的端口仍然是9528(如图所示)

因为在浏览器是看不出来的,其实已经转到3000端口,跨域请求的目的就是为了绕过浏览器的限制。

提示:target目标地址可以为http://127.0.0.1:3000,也可以写成http://localhost:3000.
IP地址127.0.0.1对每台电脑来说都是自己,localhost默认映射到127.0.0.1.
请求既可以用域名来请求也可以用IP地址,但用域名比较合适
使用域名访问的话,如果本地有hosts文件,浏览器就会先在本地找hosts文件有没有对应域名的配置,没有再向dns获取。
hosts文件就是本地保存的域名IP映射表。

main.js中加入http

import http from './utils/http'
Vue.use(http)

二、配置服务端

创建一个db目录存放数据模块models以及连接数据库文件config.js
在这里插入图片描述

创建数据类型模块

在models目录下创建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)

Schema : 一种以文件形式存储的数据库模型骨架,不具备数据库的操作能力

module.exports 对象是由模块系统创建的。在我们自己写模块的时候,需要在模块最后写好模块接口,声明这个模块对外暴露什么内容,module.exports 提供了暴露接口的方法。这种方法可以返回全局共享的变量或者方法。
调用方法eg:
var school = require('./school.js');

配置路由

Koa-router 是 koa 的一个路由中间件,它可以将请求的URL和方法(如:GET 、 POST 、 PUT 、 DELETE 等) 匹配到对应的响应程序或页面

router.prefix()方法对某一个router来说,是一个全局配置,此router的所有路径都会自动被添加该前缀。

// 引入koa-router并对其实例化
const router = require('koa-router')()
const user = require('../db/models/user')
router.prefix('/users')

router.get('/add', function (ctx, next) {
  ctx.body = 'this id 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

在app.js中挂载路由

const users = require('./routes/users')
app.use(users.routes(), users.allowedMethods())

.allowedMethods处理的业务是当所有路由中间件执行完成之后,若ctx.status为空或者404的时候,丰富response对象的header头.

关于xxx.allowedMethods()这里有更详细的解释:https://www.jianshu.com/p/fef91266a44c

接下来在运行npm run dev,出现一下界面就是连接成功了
在这里插入图片描述
到这前后端就已经连通了,下一篇文章讲解如何实现增删改查。

  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值