vue spingboot遇到的问题,请求后端以及设置代理等问题

创建 axios 实例

request.js

import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
 // baseURL: '/api',
  timeout: 9000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      })
      if (token) {
        alert('Logout')
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['Access-Token'] = token
  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  return response.data
}, errorHandler)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request as axios
}

VUE_APP_API_BASE_URL(下图三个文件,改为后端项目地址)
在这里插入图片描述
main.js

// with polyfills
import 'core-js/stable'
import 'regenerator-runtime/runtime'

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store/'
import i18n from './locales'
import axios from 'axios'
import bootstrap from './core/bootstrap'
import { VueAxios } from './utils/request'
import ProLayout, { PageHeaderWrapper } from '@ant-design-vue/pro-layout'
import themePluginConfig from '../config/themePluginConfig'

// mock
// WARNING: `mockjs` NOT SUPPORT `IE` PLEASE DO NOT USE IN `production` ENV.
import './mock'
import './core/lazy_use' // use lazy load components
import './utils/filter' // global filter
import './global.less' // global style
Vue.config.productionTip = false
Vue.prototype.$axios = axios
Vue.use(VueAxios)
// use pro-layout components
Vue.component('pro-layout', ProLayout)
Vue.component('page-container', PageHeaderWrapper)
Vue.component('page-header-wrapper', PageHeaderWrapper)

window.umi_plugin_ant_themeVar = themePluginConfig.theme

new Vue({
  router,
  store,
  i18n,
  // init localstorage, vuex
  created: bootstrap,
  render: h => h(App)
}).$mount('#app')

vue.config.js 配置代理模块

在这里插入图片描述

  devServer: {
    // development server port 8000
     port: 8000,
    // If you want to turn on the proxy, please remove the mockjs /src/main.jsL11
     proxy: {
       '/declarehelper': {
        target: 'http://localhost:8080/declarehelper',
        ws: false,
        changeOrigin: true,
         pathRewrite: {
          '^/declarehelper': ''
         }
      }
     }
  },

vue.config.js 全文

const path = require('path')
const webpack = require('webpack')
const GitRevisionPlugin = require('git-revision-webpack-plugin')
const GitRevision = new GitRevisionPlugin()
const buildDate = JSON.stringify(new Date().toLocaleString())
const createThemeColorReplacerPlugin = require('./config/plugin.config')

function resolve (dir) {
  return path.join(__dirname, dir)
}

// check Git
function getGitHash () {
  try {
    return GitRevision.version()
  } catch (e) {}
  return 'unknown'
}

const isProd = process.env.NODE_ENV === 'production'

const assetsCDN = {
  // webpack build externals
  externals: {
    vue: 'Vue',
    'vue-router': 'VueRouter',
    vuex: 'Vuex',
    axios: 'axios'
  },
  css: [],
  // https://unpkg.com/browse/vue@2.6.10/
  js: [
    '//cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.min.js',
    '//cdn.jsdelivr.net/npm/vue-router@3.1.3/dist/vue-router.min.js',
    '//cdn.jsdelivr.net/npm/vuex@3.1.1/dist/vuex.min.js',
    '//cdn.jsdelivr.net/npm/axios@0.19.0/dist/axios.min.js'
  ]
}

// vue.config.js
const vueConfig = {
  configureWebpack: {
    // webpack plugins
    plugins: [
      // Ignore all locale files of moment.js
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
      new webpack.DefinePlugin({
        APP_VERSION: `"${require('./package.json').version}"`,
        GIT_HASH: JSON.stringify(getGitHash()),
        BUILD_DATE: buildDate
      })
    ],
    // if prod, add externals
    externals: isProd ? assetsCDN.externals : {}
  },

  chainWebpack: (config) => {
    config.resolve.alias
      .set('@$', resolve('src'))

    const svgRule = config.module.rule('svg')
    svgRule.uses.clear()
    svgRule
      .oneOf('inline')
      .resourceQuery(/inline/)
      .use('vue-svg-icon-loader')
      .loader('vue-svg-icon-loader')
      .end()
      .end()
      .oneOf('external')
      .use('file-loader')
      .loader('file-loader')
      .options({
        name: 'assets/[name].[hash:8].[ext]'
      })

    // if prod is on
    // assets require on cdn
    if (isProd) {
      config.plugin('html').tap(args => {
        args[0].cdn = assetsCDN
        return args
      })
    }
  },

  css: {
    loaderOptions: {
      less: {
        modifyVars: {
          // less vars,customize ant design theme

          // 'primary-color': '#F5222D',
          // 'link-color': '#F5222D',
          'border-radius-base': '2px'
        },
        // DO NOT REMOVE THIS LINE
        javascriptEnabled: true
      }
    }
  },

  devServer: {
    // development server port 8000
     port: 8000,
    // If you want to turn on the proxy, please remove the mockjs /src/main.jsL11
     proxy: {
       '/declarehelper': {
        target: 'http://localhost:8080/declarehelper',
        ws: false,
        changeOrigin: true,
         pathRewrite: {
          '^/declarehelper': ''
         }
      }
     }
  },

  // disable source map in production
  productionSourceMap: false,
  lintOnSave: undefined,
  // babel-loader no-ignore node_modules/*
  transpileDependencies: []
}

// preview.pro.loacg.com only do not use in your production;
if (process.env.VUE_APP_PREVIEW === 'true') {
  console.log('VUE_APP_PREVIEW', true)
  // add `ThemeColorReplacer` plugin to webpack plugins
  vueConfig.configureWebpack.plugins.push(createThemeColorReplacerPlugin())
}

module.exports = vueConfig

调用请求后台

不带参数的情况

this.$axios({
                    methods: 'GET',
                    url: '/declarehelper/basicSettings/queryBasicSettings'
                }).then(res => {
                    // console.log(res.data.message, res)
                    this.path = res.data.result.path
                    this.description = res.data.result.description
                })

带参数的情况

  this.$axios({
                    methods: 'GET',
                    url: '/declarehelper/basicSettings/save',
                    params: {
                        path: this.path,
                        description: this.description
                    }
                }).then(res => {
                    alert(res.data.message)
                    console.log(res.data.message, res)
                })

created 初始化之前运行,相当于ajax初始化函数

    export default {
        data () {
            return {
                data: [],
                path: '',
                description: ''
            }
        },
        methods: {
            mounted: function () {

            },
            sumbit: function () {
                if (this.path === null || this.path === '') {
                    alert('请输入本地报文存放路径')
                    return
                }
                this.$axios({
                    methods: 'GET',
                    url: '/declarehelper/basicSettings/save',
                    params: {
                        path: this.path,
                        description: this.description
                    }
                }).then(res => {
                    alert(res.data.message)
                    console.log(res.data.message, res)
                })
            },
            init: function () {
                this.$axios({
                    methods: 'GET',
                    url: '/declarehelper/basicSettings/queryBasicSettings'
                }).then(res => {
                    // console.log(res.data.message, res)
                    this.path = res.data.result.path
                    this.description = res.data.result.description
                })
            }
        },
        created () {
            this.init()
        }
    }

页面为

<template>
  <div class="account-settings-info-view">
    <a-row :gutter="16">
      <a-col :md="24" :lg="16">

        <a-form layout="vertical">
          <a-form-item label="本地报文存放路径">
            <a-input placeholder="请输入本地报文存放路径" v-model="path" allow-clear/>
          </a-form-item>
          <a-form-item label="报文说明">
            <a-textarea rows="4" placeholder="请输入报文说明" v-model="description" allow-clear/>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="sumbit()">确定</a-button>
          </a-form-item>
        </a-form>
      </a-col>
    </a-row>
  </div>
</template>

<script>
    export default {
        data () {
            return {
                data: [],
                path: '',
                description: ''
            }
        },
        methods: {
            mounted: function () {

            },
            sumbit: function () {
                if (this.path === null || this.path === '') {
                    alert('请输入本地报文存放路径')
                    return
                }
                this.$axios({
                    methods: 'GET',
                    url: '/declarehelper/basicSettings/save',
                    params: {
                        path: this.path,
                        description: this.description
                    }
                }).then(res => {
                    alert(res.data.message)
                    console.log(res.data.message, res)
                })
            },
            init: function () {
                this.$axios({
                    methods: 'GET',
                    url: '/declarehelper/basicSettings/queryBasicSettings'
                }).then(res => {
                    // console.log(res.data.message, res)
                    this.path = res.data.result.path
                    this.description = res.data.result.description
                })
            }
        },
        created () {
            this.init()
        }
    }
</script>

<style scoped>

</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mcxiaochi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值