vue+node(express)作中间层开发一

2021年09月16日 阅读数:8
这篇文章主要向大家介绍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.pngcss

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文件中编辑vue

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文件node

<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.pngwebpack

node端

安装npm install -g express-generator@4
在vueapp下新建server文件夹,切换到server文件夹,执行express node_api && cd node_api ,会新建一个node_api的项目,而后安装依赖npm installios

执行npm start启动expressweb

$ npm start

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

在页面server/node_api/routes/index.js配置路由vue-cli

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.pngexpress

安装nodemon实现nodejs热启动 npm install --save-dev nodemon,用nodemon指令提到node指令便可
安装cross-env实现环境变量设置 npm install --save-dev cross-env,编辑server/node_api/package.jsonnpm

{
  "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,和前端统一