vuecli3、vuecli4+springboot跨域访问设置+axios的(get、post)发送和接收json数据

1.spingboot全局允许跨越:

CrosConfig.java
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class CrosConfig extends WebMvcConfigurationSupport {

    //跨域访问
    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedHeaders("*")
                .allowedOrigins("*")
                .allowedMethods("*");
    }

}

2.vuecli3、vuecli4跨域设置:

①安装axios

直接使用命令:vue add axios

plugins目录下生成axios.js,并在main.js中自动引入。

②配置axios.js内的拦截:

axios.js

"use strict";

import Vue from 'vue';
import axios from "axios";

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  baseURL: "/api",
  timeout: 60 * 1000, // Timeout
  withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {
    // Do something with response data
    return response;
  },
  function (error) {
    // Do something with response error
    return Promise.reject(error);
  }
);

Plugin.install = function (Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin)

export default Plugin;

③配置代理

vue.config.js

const port = 8900;

module.exports = {
  devServer: {
    port,
    open: false,
    overlay: {
      warnings: false,
      errors: true
    },
    // 配置代理
    proxy: {
      "/api": {
        target: 'http://192.168.100.180:8900/cbhs/',
        changeOrigin: true, // 是否改变域名
        ws: true,
        pathRewrite: {
          // 路径重写
          "^/api": ""
        }
      }
    }
  },
  "transpileDependencies": [
    "vuetify"
  ],

}

3.axios.get

①后端

class上加

@RestController
    @RequestMapping("/dmjsz/pzgl/pzfh/test")
    public Result pzfhInit(@RequestParam String bmbh) {
        return pzglService.getBmInfo(bmbh);
    }

②前端vue

    <div>
      <v-btn color="info" @click="getAxios">测试getaxios</v-btn>
      <v-btn color="info" @click="postAxios">测试postaxios</v-btn>
      <div>{{responsedata}}</div>
    </div>
    getAxios() {
      let self = this;
      let url = '/dmjsz/pzgl/pzfh/test';
      let params = new URLSearchParams();
      params.append('bmbh', '080700');
      axios
        .get(url, { params: params })
        .then(function (response) {
          self.responsedata = response.data;
          console.log('**getAxios**' + self.responsedata.data.l_bmmc);
        })
        .catch((error) => {
          console.log(error);
        });
    },

4.axios.post

①后端

    @RequestMapping(value = "/dmjsz/pzgl/pzfh/test", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public Result pzfhInit(@RequestBody Map<String,String> jsonmap) {
        Result rs = new Result();
            System.out.println("**jsonParam**"+jsonmap.toString());
            rs = pzglService.getBmInfo(jsonmap.get("bmbh"));
        return rs;
    }

②前端vue

    <div>
      <v-btn color="info" @click="getAxios">测试getaxios</v-btn>
      <v-btn color="info" @click="postAxios">测试postaxios</v-btn>
      <div>{{responsedata}}</div>
    </div>

 

    postAxios() {
      let self = this;
      let url = '/dmjsz/pzgl/pzfh/test';
      let data = { bmbh: '010100' };
      axios
        .post(url, data)
        .then(function (response) {
          self.responsedata = response.data;
          console.log('**postAxios**' + self.responsedata.data.l_bmmc);
        })
        .catch((error) => {
          console.log(error);
        });
    },

 

©️2020 CSDN 皮肤主题: 像素格子 设计师:CSDN官方博客 返回首页