1. 封装在src/utils/axios

封装在src/utils/axios



import axios from 'axios'

let httpService = axios.create({
  baseURL: process.env.BASE_URL,
  timeout: 5000
})

// 拦截请求
httpService.interceptors.request.use(config => {
  if (localStorage.getItem('token')) {
    config.headers.token = localStorage.getItem('token')
  }
  return config;
},err => {
  Promise.reject(err);
})

// 拦截响应
httpService.interceptors.response.use(response => {
  console.log(response)
  console.log('请求成功')
  return response;
},err => {
  return Promise.reject(err);
})

// get请求的封装
export function get(url, params={}, headers = {'Content-Type':'application/json'}) {
  return new Promise((resolve,reject) => {
    httpService({
      url: url,
      method: 'get',
      params: params,
      headers: headers,
    }).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    })
  })
}

// post请求封装 
export function post(url, data = {}, headers = {'Content-Type':'application/json'}) {
  return new Promise((resolve,reject) => {
    httpService({
      url: url,
      method:'post',
      data: JSON.stringify(data),
      headers: headers
    }).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    })
  })
}

export default {
  get,
  post,
}

2. 封装service在src/service/login/login.js

import {get, post} from '../../utils/axios.js'

export function loginService(data) {
  return post(
    '/login',
    data,
  )
}

export default {
	loginService
}

3. 在vue中使用service在src/view/login/Login.vue

import { loginService } from '../../service/login/login.js'
export default {
  name: 'LoginForm',
  data: () => ({
    loginForm: {
      userId: 1,
      password: 'abc123',
    },
  }),
  computed: {
    rules () {
      return {
        userId: {
          required: true,
          message: '账号不能为空',
          trigger: 'blur'
        },
        password: {
          required: true,
          message: '密码不能为空',
          trigger: 'blur'
        },
      }
    },
  },
  methods: {
    login() {
      loginService(this.loginForm)
        .then(successResponse => (
          this.$router.push('/news')
        ))
        .catch(failResponse => {
          console.log(failResponse)
        })
    },
  },
}

4. 配置代理

config/index.js

    proxyTable: {
      '/api': {
        target: 'http://localhost:8082/',
        changeOrigin: true,
        pathRewrite: {
          '^/api': '/'
        }
      }
    },

config/dev.env.js

'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  BASE_URL: '"http://localhost:8080/api"',
})

Logo

前往低代码交流专区

更多推荐