express搭建純後臺,前臺使用vue-cli腳手架

注意:後臺服務更改以後須要重啓服務;前端配置文件更改以後也須要從新跑命令npm run dev
1、使用express提供後臺服務,輸出接口
後臺目錄結構:
express搭建純後臺,前臺使用vue-cli腳手架前端

main.jsvue

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")
})

---解釋---:node

(1)、app.get()表示接收全部前端來的get請求方式,同理,app.post(),app.delete()分別表示接受前端發來的post請求與delete請求方式。mysql

(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參數表示的接口執行一些操做,這些操做寫在第二個參數即回調函數內。webpack

(3) app.get()中的第二個參數---回調函數:該回調函數接受3個參數,按照大多數人的不成文的書寫慣例,這三個傳參寫做req, res, next。第一個參數表示http請求對象(request),第二個參數表示response對象,第三個參數是next函數,表示將控制權交給下一個中間件。next有點複雜不詳說,只要記住一個請求結束後,不要後面寫next(),常見的res.send(),res.json()都屬於請求結束,後面不要再寫next()了.ios

(4)res.json(obj) 表示返回一個json對象,該對象的詳細數據就是括號裏的東西啦。web

2、前端使用vue-cli腳手架
前端目錄結構:
express搭建純後臺,前臺使用vue-cli腳手架
一、先解決跨域問題
在config/index.js文件裏面的module.exports對象裏面的proxyTable裏面加上如下代理:sql

proxyTable: {
    '/gsafetyapi': {
        target: 'http://127.0.0.1:8888/', //要代理的服務地址,要加http
        changeOrigin: true,  //是否跨域
        secure: false, //若是是https接口,須要配置這個參數
        timeout: 480000,
        pathRewrite: {
            '^/gsafetyapi': ''  //這裏理解成用gsafetyapi代替target裏面的地址
        }
    },
},

二、封裝axios和接口地址集合
新建文件夾plugins
express搭建純後臺,前臺使用vue-cli腳手架
http.jsmongodb

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.jsvue-cli

export default {
  getCompanyDepartmentTree: "/api/v1/user-center-service/companyDepartment/getCompanyDepartmentTree", //獲取組織架構數據
  getUserInfo:"/getUserInfo"
}

三、全局註冊封裝好的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/>'
})

四、調接口:http://127.0.0.1:8888/getUserInfo

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

3、數據庫使用mongodb
一、安裝,直接安裝在c盤下
二、配置環境變量
三、建立數據庫文件的存放位置
在D盤下新建mongodb文件夾,
mongodb文件夾裏面新建data文件夾,data文件夾裏面新建db和log文件夾
mongodb文件夾裏面新建mongo.config配置文件,文件內容:

##數據文件  此處=後對應到數據所存放的目錄
dbpath=d:\mongodb\data\db
##日誌文件  此處=後對應到日誌文件所在路徑
logpath=d:\mongodb\data\log\mongodb.log
##錯誤日誌採用追加模式,配置這個選項後mongodb的日誌會追加到現有的日誌文件,而不是重新建立一個新文件
logappend=true 
#啓用日誌文件,默認啓用
journal=true 
#這個選項能夠過濾掉一些無用的日誌信息,若須要調試使用請設置爲false
quiet=true 
#端口號 默認爲27017
port=27017

四、
net start MongoDB 開啓服務
net stop MongoDB 關閉服務
五、如今搭建的是本地數據庫,數據庫地址:http://localhost:27017/

六、mongoose 數據模型
直接用 node.js 也能夠鏈接數據庫進行讀寫,但mongoose 這個插件除了封裝這個基本功能以外,還提供了不少其餘的服務。

安裝:npm install mongoose --save
var mongoose = require('mongoose');
//連接數據庫
mongoose.connect('mongodb://localhost:27017/db',function(err){
    if(err){
        console.log('數據庫鏈接失敗')
    }else{
        console.log('數據庫鏈接成功')
        var server = app.listen(8888, function(){
            console.log("Server is running on http://localhost:8888");
        });
    }
});

七、創建schema,相似於一個collection集合的概念,相似於mysql的一張表,定義schema,就是定義這張表的表結構,要存什麼格式的數據,每一條數據都是這張表的一行,
注意:這種schema不具有操做數據庫的能力

let mongoose = require('mongoose');
let userScheam = new mongoose.Schema({
    //帳戶名
    account:String,
    pass:String,
    checkPass:String,
    age:Number
})
module.exports = userScheam;

八、定義好了Schema,接下就是生成Model。
model是由schema生成的模型,能夠對數據庫進行操做

//表有了,下面須要藉助model,來對數據庫的表進行操做
let mongoose = require('mongoose');
let userSchema = require('../schemas/userSchema');
module.exports = new mongoose.model('User',userSchema); //User是給這個模型起的名字,後面是要操做的那個表的表名
//User才具備了對錶進行增刪改查的api

九、在路由文件前面,引入該model,而後就可使用var User = require('./models/userModel');User.save(); User.find();等等增刪改查方法

相關文章
相關標籤/搜索