vue封装axios请求springboot 及跨域问题

65 篇文章 1 订阅
47 篇文章 0 订阅

vue页面

安装element-ui

npm install element-ui --save

 

安装axios插件

npm install axios --save

创建个http.js

 

import axios from 'axios';
import { Message } from 'element-ui';

axios.defaults.timeout = 5000; //超时终止请求
axios.defaults.baseURL ='http://localhost:8087/'; //配置请求地址


//http request 拦截器
axios.interceptors.request.use(
  config => {
    // const token = getCookie('名称');注意使用的时候需要引入cookie方法,推荐js-cookie
    config.data = JSON.stringify(config.data);
    config.headers = {
      /*'Content-Type':'application/x-www-form-urlencoded'*/
      'Content-Type':'application/json;charset=UTF-8'
    }
    // if(token){
    //   config.params = {'token':token}
    // }
    return config;
  },
  error => {
    return Promise.reject(err);
  }
);


//http response 拦截器

axios.interceptors.response.use(
  response => {
    if(response.data.errCode ==2){
      router.push({
        path:"/login",
        querry:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
      })
    }
    return response;
  },
  error => {
    Message({
      Message:error.message,
      type:'error',
      duration:5*1000
    });
    return Promise.reject(error)
  }
)



/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch(url,params={}){
  return new Promise((resolve,reject) => {
    axios.get(url,{
      params:params
    })
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.post(url,data)
      .then(response => {
        resolve(response.data);
      },err => {
        reject(err)
      })
  })
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.patch(url,data)
      .then(response => {
        resolve(response.data);
      },err => {
        reject(err)
      })
  })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.put(url,data)
      .then(response => {
        resolve(response.data);
      },err => {
        reject(err)
      })
  })
}

main.js  加入

import {post,fetch,patch,put} from "../static/http.js";
Vue.prototype.$axios=axios;
Vue.prototype.$post=post;
Vue.prototype.$fetch=fetch;
Vue.prototype.$patch=patch;
Vue.prototype.$put=put;

import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
// table 的样式需要手动引入
import 'element-ui/lib/theme-chalk/icon.css'
import 'element-ui/lib/theme-chalk/table.css'
import 'element-ui/lib/theme-chalk/table-column.css'
import store from './store'
import Vuex from 'vuex'

import axios from 'axios'
import {post,fetch,patch,put} from "../static/http.js";
Vue.prototype.$axios=axios;
Vue.prototype.$post=post;
Vue.prototype.$fetch=fetch;
Vue.prototype.$patch=patch;
Vue.prototype.$put=put;
Vue.config.productionTip = false
Vue.use(ElementUI);
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
Vue.use(Vuex);
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})

vue页面请求

 methods:{
          
        SubmitLogin:function () {
          var params = {
            userid:1001
          };
          this.$post("tuser/findId",params)
            .then((response)=>{
               alert(JSON.stringify(response))
            })
        }
      },

 

springboot后端:

Controller

//前端传过来的是json类型的值  需要加上这个注解@RequestBody 不然接收不到值
 @RequestMapping("findId")
    @ResponseBody
    public TUser findId(@RequestBody TUser tUser){  
        System.out.println(tUser.getUserid());
        return tuserService.getTuseId(tUser.getUserid());
    }

service


    @Override
    public TUser getTuseId(Integer id) {
        return tuserMapper.getTuseId(id);
    }

mapper

  /**
     * 根据id查询
     * @param id
     * @return
     */
    public TUser getTuseId(Integer id);

mapper xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.spring.mybatis.mapper.TuserMapper" >
  <resultMap id="BaseResultMap" type="com.spring.mybatis.entity.TUser" >
    <!--
      WARNING - @mbg.generated
    -->
    <id column="userId" property="userid" jdbcType="INTEGER" />
    <result column="userName" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="phone" property="phone" jdbcType="VARCHAR" />
  </resultMap>

<select id="getTuseId" resultMap="BaseResultMap" parameterType="int">
  SELECT  * FROM  t_user where userid=#{id};
</select>

</mapper>

执行后浏览器控制台出现了

跨域问题

前端config下的index.js加上

解决方法:

 后端建个CorsConfig

package com.spring.mybatis.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * WebMvcConfigurerAdapter
 *
 * @author heng
 * @version 1.0.0
 **/

/**
 * 解决vue+spring boot跨域问题
 */
@Configuration
public class CorsConfig  extends WebMvcConfigurerAdapter{

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        System.out.println("----------------------");
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600);
    }


}

 

最后运行:

还有一种方法 加上过滤器 过滤

启动类代码加上 @ServletComponentScan

package com.spring.mybatis;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.ComponentScan;

/**
 * Application
 *
 * @author heng
 * @version 1.0.0
 **/
@SpringBootApplication
@MapperScan("com.spring.mybatis.mapper")
@ComponentScan("com.spring.mybatis")
@ServletComponentScan
public class Application   {

    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

创建过滤器

ACAFilter

package com.spring.mybatis.filter;

import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 跨域的设置问题
 * @author tonywu
 * @version v1.0.0
 */

//@Component   //在启动类加了@ServletComponentScan无需加这个了
@Order(3)//设置优先级加载
//@ServletComponentScan  //加载启动类上了
@WebFilter(urlPatterns = "/*",filterName = "ACAFilter")
public class ACAFilter implements Filter {

    /**
     * 初始化
     * @param filterConfig FilterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    /**
     * 过滤
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        //response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", ":x-requested-with,content-type");
        //((HttpServletResponse)servletResponse).setHeader("Access-Control-Allow-Origin", "*");
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("to access control allow origin");
    }

    /**
     * 销毁
     */
    @Override
    public void destroy() {
    }
}

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值