8.vwe开发之axios向后台发送请求

场景

前提条件:基于webpack+ vue+ express后台搭建一个完整的页面后请求已经完成。前端需要向后台请求数据从而
填充前端页面。

一直页面vue代码如下,详情请看blog-list.vue

<template>
    <div>
        <table>
            <thead>
            <tr>
                <th>title</th>
                <th>context</th>
                <th>author</th>
                <th>createTime</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="blog in blogs" v-bind:key="blog.id">
                <td>{{blog.title}}</td>
                <td>{{blog.context}}</td>
                <td>{{blog.author}}</td>
                <td>{{blog.createTime}}</td>
            </tr>
            </tbody>
        </table>
    </div>
</template>

<script>
  // import {ApiService} from '../js/apiService.js'
  //
  // const apiService = new ApiService();

  export default {
    name: "blog-list",
    data() {
      return {
        blogs: [],
        numberOfBlogs: 0
      }
    },
    // methods: {
    //   getBlogs() {
    //     apiService.getBlogs().then((resp) => {
    //       this.blogs = resp;
    //       this.numberOfBlogs = resp.length;
    //     });
    //   }
    // },
    // mounted() {
    //   this.getBlogs();
    // }
  }
</script>

<style scoped>

</style>

注释的代码是后面用到的代码

运行后应该没有任何数据,只有标题

目的

我们需要数据,从后台获取数据,这里我们从express后台接口获取数据。

步骤

为了实现我们的目的,我们需要用到如下工具axios,这是一个类似ajax来进行前端发送http请求的工具包,
安装axios,这里用的版本为0.18.0,安装方式为

  1. 在package.json的devDependencies中添加:
axios": "^0.18.0",
  1. 执行命令行
npm i --save-dev axios@0.18.0

当然在可执行发送命令之前,我们得有api可请求,所以我们需要在server端生成接口,为了能让express服务器可以识别请求
我们需要在server-dev.js中增加 如下引入

let createError = require('http-errors');
let cookieParser = require('cookie-parser');
let logger = require('morgan');

然后在app中使用引入

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());

这样我们的express服务器端就有能力识别http请求了。但是这还是不够的,我们需要做到,那个请求对应那个
处理方式,那么我们需要使用到express自带的Router了,router顾名思义,路由。我们先在src下面建立一个用来
存储请求路径的ex-router(express-router)文件夹,在下面建立一个名叫index.js的文件,代码如下

let express = require('express');
let router = express.Router();
//'blog-list'是指路径,后面是指处理函数
router.get('/blog-list', (req, res, next) => {
  let blog1 = {
    id:1,
    title: 'blog1',
    context: "hello,world",
    author: 'rb.x',
    createTime: '2019-05-06 12:00'
  };
  let blog2 = {
    id:2,
    title: 'blog2',
    context: "hello,world2",
    author: 'rb.x',
    createTime: '2019-05-06 21:00'
  };
  let blogs = [blog1, blog2];
  //为了方便前端处理,我们返回json格式的数据
  res.send(JSON.stringify(blogs));
});

module.exports = router;

这样的话,我们就定义了路由,如果需要增加路径的话,仿照blog-list就可以了。

现在我们定义好了路由,但是express服务器是不知道,我们需要导入到server-dev.js中告诉它。引入路由js文件

import router from '../ex-router/ex-router';

同时app总使用路由

app.use(router);

最后,server-dev.js的代码如下:

import path from 'path'
import express from 'express'
import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import config from '../../webpack.dev.config.js'

let createError = require('http-errors');
let cookieParser = require('cookie-parser');
let logger = require('morgan');
import router from '../ex-router/ex-router';


const app = express(),
  DIST_DIR = __dirname,
  HTML_FILE = path.join(DIST_DIR, 'index.html'),
  compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, {
  publicPath: config.output.publicPath
}));

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(router);

app.use(webpackHotMiddleware(compiler, {
  noInfo: false,
  publicPath: config.output.publicPath
}));

app.use('/public', express.static('public'));
app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
});

const PORT = process.env.PORT || 8090;
app.listen(PORT, (err) => {
  if (err) {
    console.log(err);
    return;
  }
  console.log(`App listening to ${PORT}....`)
  console.log('Press Ctrl+C to quit.')
})

这个时候,我们重新启动,就可以在浏览器输入:http://localhost:8090/blog-list
就可以获取到一串字符串json了

[{"id":1,"title":"blog1","context":"hello,world","author":"rb.x","createTime":"2019-05-06 12:00"},{"id":2,"title":"blog2","context":"hello,world2","author":"rb.x","createTime":"2019-05-06 21:00"}]

好了,既然接口已经有了,那么我们需要在前端调用这个接口,为了方便调用,我们需要封装一个apiService来统一一下调用接口,
我们在/src/js中创建一个apiService.js,代码如下

//导入axios
import axios from 'axios'
//定义主机,定义别的主机可能会报跨域错误
const API_URL = "http://localhost:8090";

//定义并且曝光出一个类
export class ApiService {
    constructor() {
    }

//定义一个方法
    getBlogs() {
        const url = `${API_URL}/blog-list/`;
        return axios.get(url).then((res) => res.data);
    }

}

好了,类封装好了,如何引入在vue中呢?很简单直接在vue中的js中引入,如注释所述

<template>
    <div>
        <table>
            <thead>
            <tr>
                <th>title</th>
                <th>context</th>
                <th>author</th>
                <th>createTime</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="blog in blogs" v-bind:key="blog.id">
                <td>{{blog.title}}</td>
                <td>{{blog.context}}</td>
                <td>{{blog.author}}</td>
                <td>{{blog.createTime}}</td>
            </tr>
            </tbody>
        </table>
    </div>
</template>

<script>
    //引入接口辅助类
  import {ApiService} from '../js/apiService.js'
    //定义一个对象
  const apiService = new ApiService();

  export default {
    name: "blog-list",
    data() {
      return {
        blogs: [],
        numberOfBlogs: 0
      }
    },
      //定义方法
    methods: {
      getBlogs() {
          //调用接口获取数据,并且更新vue页面数据
        apiService.getBlogs().then((resp) => {
          this.blogs = resp;
          this.numberOfBlogs = resp.length;
        });
      }
    },
      //在vue被渲染的时候调用方法
    mounted() {
      this.getBlogs();
    }
  }
</script>

<style scoped>

</style>

这个时候,页面就会有数据了,理论上并不不要重新启动,因为HRM的缘故。

详情请看代码!

下一篇:9.vwe开发之支持markdown

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值