express搭建纯后台,前台使用vue-cli脚手架

注意:后台服务更改之后需要重启服务;前端配置文件更改之后也需要重新跑命令npm run dev
一、使用express提供后台服务,输出接口
后台目录结构:
express搭建纯后台,前台使用vue-cli脚手架

main.js

var express = require('express');
var app = express();
app.get('/', function (req, res) {
    res.send('Hello World');
})
app.get('/getUserInfo', function(req, res, next){  //用于前台调用的接口,地址:http://127.0.0.1:8888/getUserInfo
    console.log('get用户请求数据为:');
    console.log(req.query);
    res.json({
        code:200,
        data:{
            message:'你好'
        },
        message:'success'
    });
});
var server = app.listen(8888, function () {
    var host = server.address().address
    var port = server.address().port
    console.log(host,port)
    console.log("your application is running on http://localhost:8888")
})

---解释---:

(1)、app.get()表示接收所有前端来的get请求方式,同理,app.post(),app.delete()分别表示接受前端发来的post请求与delete请求方式。

(2)、app.get(path, callback [, callback ...]):传参,第一个参数是路径,后面的参数都是是回调函数,可以放1个或者多个回调函数,一般只用到1个回调,本例也只用了1个回调。官方对这个方法的解释是:Routes HTTP GET requests to the specified path with the specified callback functions,意即‘用指定回调方法向指定路径发送http get请求’,通俗讲就是对path参数表示的接口执行一些操作,这些操作写在第二个参数即回调函数内。

(3) app.get()中的第二个参数---回调函数:该回调函数接受3个参数,按照大多数人的不成文的书写惯例,这三个传参写作req, res, next。第一个参数表示http请求对象(request),第二个参数表示response对象,第三个参数是next函数,表示将控制权交给下一个中间件。next有点复杂不详说,只要记住一个请求结束后,不要后面写next(),常见的res.send(),res.json()都属于请求结束,后面不要再写next()了.

(4)res.json(obj) 表示返回一个json对象,该对象的详细数据就是括号里的东西啦。

二、前端使用vue-cli脚手架
前端目录结构:
express搭建纯后台,前台使用vue-cli脚手架
1、先解决跨域问题
在config/index.js文件里面的module.exports对象里面的proxyTable里面加上以下代理:

proxyTable: {
    '/gsafetyapi': {
        target: 'http://127.0.0.1:8888/', //要代理的服务地址,要加http
        changeOrigin: true,  //是否跨域
        secure: false, //如果是https接口,需要配置这个参数
        timeout: 480000,
        pathRewrite: {
            '^/gsafetyapi': ''  //这里理解成用gsafetyapi代替target里面的地址
        }
    },
},

2、封装axios和接口地址集合
新建文件夹plugins
express搭建纯后台,前台使用vue-cli脚手架
http.js

import axios from 'axios';
import apiConfig from "./api.js"
import qs from 'qs'

axios.defaults.baseURL = process.env.NODE_ENV === 'development' ? 'gsafetyapi' : '';  //开发的时候加代理,生产环境不用加代理
// 请求拦截
axios.interceptors.request.use(config => {
  // 1. 这个位置就请求前最后的配置
  // 2. 当然你也可以在这个位置 加入你的后端需要的用户授权信息
  return config
}, error => {
  return Promise.reject(error)
})
// 响应拦截
axios.interceptors.response.use(response => {
  // 请求成功
  // 1. 根据自己项目需求定制自己的拦截
  // 2. 然后返回数据
  return response;
}, error => {
  // 请求失败
  if (error && error.response) {
    switch (error.response.status) {
      case 400:
        // 对400错误您的处理\
        break
      case 401:
        // 对 401 错误进行处理
        break
      default:
        // 如果以上都不是的处理
        return Promise.reject(error);
    }
  }
})
export default {
  /**
   * get 请求
   * @param api_name 接口路由
   * @param params 接口参数
   * @param time 如果请求话费了超过 `time` 的时间,请求将被中断
   * @returns {AxiosPromise<any>}
   */
  // get(apiKey, data) {
  //   return axios.get(apiConfig[apiKey], data);
  // },
  get(api_name, params, time) {
    let url = apiConfig[api_name];
    return axios({
      method: 'get',
      url: url,
      params: params,
      timeout: time || 60000,
    })
  },
  /**
   * post 请求
   *
   * @param api_name 接口路由
   * @param params 接口参数
   * @param time 如果请求话费了超过 `time` 的时间,请求将被中断
   * @returns {AxiosPromise<any>}
   */
  post(api_name, params, time) {

    let url = apiConfig[api_name];
    return axios({
      method: 'post',
      url: url,
      params: qs.stringify(params),
      timeout: time || 60000,
    })
  },
}

封装api的文件
api.js

export default {
  getCompanyDepartmentTree: "/api/v1/user-center-service/companyDepartment/getCompanyDepartmentTree", //获取组织架构数据
  getUserInfo:"/getUserInfo"
}

3、全局注册封装好的axios

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
// 已在webpack.base.conf中使用别名设置了要使用import命令加载的Vue构建版本(仅运行时或独立运行)
import Vue from 'vue'
import App from './App'
import router from './router'
import http from '../plugins/http'
Vue.config.productionTip = false
Vue.prototype.$http = http;

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

4、调接口:http://127.0.0.1:8888/getUserInfo

created () {
    this.$http
        .get("getUserInfo",{name:'kate'}).then(res => {
            console.log(res)
        });
  }

猜你喜欢

转载自blog.51cto.com/9161018/2448223