vue+node(express)做中間層開發一

前提條件安裝:

  • vue v2.9.6
  • vue-cli
  • iview
  • node v15.4
  • express v4.16.1
  • axios v0.18.0
  • cors

采用的結構為前端Vue項目,內包一個node服務


Screen Shot 2020-12-19 at 09.30.41.png

vue端

vue init webpack vueapp //新建一個vueapp項目,采用默認配置即可

執行 npm run dev啟動vue

$ npm run dev

> vueapp@1.0.0 dev /Users/mac/dongzhiqin/vueapp
> webpack-dev-server --inline --progress --config build/webpack.dev.conf.js

 13% building modules 32/37 modules 5 active ...ers/mac/dongzhiqin/vueapp/src/App.vue{ parser: "babylon" } is deprecated; we now treat it as { parser: "babel" }.
 95% emitting                                                       i
 DONE  Compiled successfully in 4924ms                      6:48:54 PM

 I  Your application is running here: http://localhost:8080

引入iview和axios,在main.js文件中編輯

import axios from 'axios'
import ViewUI from 'view-design'
import 'view-design/dist/styles/iview.css'
Vue.prototype.$axios = axios // 把axios注冊為原型屬性
Vue.use(ViewUI)

編輯helloworld.vue文件

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <button type="button" name="button" v-on:click="getmsg">send</button>
    <button type="button" name="button" v-on:click="postmsg">send</button>
    <Button>Default</Button>
    <Button type="primary">Primary</Button>
    <Button type="dashed">Dashed</Button>
    <Button type="text">Text</Button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods: {
    getmsg () {
      this.$axios.get('/api/request?dong=123').then(function (res) {
        console.log('res=', res)
      })
    },
    postmsg () {
      this.$axios.post('/api/postrequest', {name: '123'}).then(function (res) {
        console.log('post res = ', res)
      })
    }
  }
}
</script>

此時用到了iview組件button,并且設置了兩個數據調用的方法,界面如下圖


Screen Shot 2020-12-19 at 10.16.20.png

node端

安裝npm install -g express-generator@4
在vueapp下新建server文件夾,切換到server文件夾,執行express node_api && cd node_api ,會新建一個node_api的項目,然后安裝依賴npm install。

執行npm start啟動express

$ npm start

> node-api@0.0.0 start /Users/mac/dongzhiqin/vueapp/server/node_api
> node ./bin/www

在頁面server/node_api/routes/index.js配置路由

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/hi', function(req, res, next) {
  req.name = 'kim';
  next();
})

router.get('/hi', function(req,res) {
  res.send(`hello ${req.name}`)
})

router.get('/request', function(req,res,next){
  res.send(req.query)
})

router.post('/postrequest', function(req, res, next){
  res.send(req.body)
})

router.get('/user', function(req, res, next) {
  console.log('req: ',req)
  res.send({
    name: 'kim',
    address: '廣州海珠區',
  })
})

module.exports = router;

用瀏覽器或者postman訪問localhost:3000(默認端口是3000),可以看到有返回了


Screen Shot 2020-12-19 at 10.06.27.png

安裝nodemon實現nodejs熱啟動 npm install --save-dev nodemon,用nodemon指令提到node指令即可
安裝cross-env實現環境變量設置 npm install --save-dev cross-env,編輯server/node_api/package.json

{
  "name": "node-api",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start:dev": "cross-env NODE_ENV=development nodemon ./bin/www",
    "start:prod": "cross-env NODE_ENV=production node ./bin/www"
  },
  "dependencies": {
    "cookie-parser": "~1.4.4",
    "cors": "^2.8.5",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "jade": "~1.11.0",
    "morgan": "~1.9.1"
  },
  "devDependencies": {
    "cross-env": "^7.0.3",
    "nodemon": "^2.0.6"
  }
}

解決跨域

此時前端展示有了,后端數據也有了,還需要解決跨域問題,因為端口一個是8080,一個是3000 。
在express的app.js文件內編輯:

//跨域問題解決方面
const cors = require('cors');  
app.use(cors({  
    origin:['http://localhost:8080'],
    methods:['GET','POST'],
}));
//跨域問題解決方面
app.all('*',function (req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
 next(); 
});

設置vue的代理,編輯config/index.js

    proxyTable: {
      '/api': {
        target: 'http://localhost:3000/',
        ChangeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    },

重啟一下express,此時在界面點擊按鈕,即可看到服務器回傳的數據了


Screen Shot 2020-12-19 at 10.24.38.png

后續

接下來可以做的事

  1. 用express實現接口轉發的功能
  2. 把express中間層獨立出來
  3. 服務端也使用axios,和前端統一
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容