最新公告
  • 欢迎您光临起源地模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • vue+node(express)做中间层开发一

    正文概述 掘金(元素师)   2021-01-15   540

    前提条件安装:

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

    采用的结构为前端Vue项目,内包一个node服务 vue+node(express)做中间层开发一

    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,并且设置了两个数据调用的方法,界面如下图 vue+node(express)做中间层开发一

    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),可以看到有返回了 vue+node(express)做中间层开发一

    安装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,此时在界面点击按钮,即可看到服务器回传的数据了 vue+node(express)做中间层开发一

    后续

    接下来可以做的事

    1. 用express实现接口转发的功能
    2. 把express中间层独立出来
    3. 服务端也使用axios,和前端统一

    起源地下载网 » vue+node(express)做中间层开发一

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元