VUE 封装 network

1. 用脚手架创建一个VUE项目

2. 安装axios

npm install axios

3. 在 src 目录下增加 network目录

4. 在network目录下增加文件 request.js

import axios from 'axios'

export const request = config => {
  const instance = axios.create({
    baseURL: 'http://localhost',
    timeout: 5000
  })
  instance.interceptors.request.use(config => {
    console.log("请求成功进行拦截", config);
    return config
  }, err => {
    console.log("请求失败进行拦截", err)
  })
  instance.interceptors.response.use(res => {
    console.log("响应成功进行拦截", res);
    return res.data
  }, err => {
    console.log("响应失败进行拦截", err);
  })
  return instance(config)
}

5. App.vue 中使用

<template>
  <h1>{{name}}</h1>
</template>

<script>
import {request} from './network/request'

export default {
  name: 'App',
  data() {
    return {
      name: ''
    }
  },
  created() {
    request({
      url: '/hello',
      params: {
        id: 1
      }
    }).then(res => {
      this.name = res;
    });
  }
}
</script>

<style>
h1 {
  text-align: center;
  color: orange;
}
</style>


  1. 后端代码,SpringBoot项目
package net.biancheng.www.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin
@RestController
public class HelloController {

	private static final Map<Integer, String> MAP = new HashMap<>();
	static {
		MAP.put(1, "苹果");
		MAP.put(2, "香蕉");
	}
	
	@GetMapping("/hello")
	public String hello(int id) {
		return MAP.get(id);
	}
	
}

注:有时遇到vue项目没有错误,但启动失败的情况,可能是依赖版本不对,可以从一个能启动的项目中替换package-lock.json

posted @ 2022-05-20 22:45  君子键  阅读(147)  评论(0)    收藏  举报