跨域springMVC+axios

 1.配置拦截器

 	<mvc:interceptors>
		<mvc:interceptor>
			<!-- 所有的请求都进入拦截器 -->
			<mvc:mapping path="/**" />
			<!-- 配置具体的拦截器 -->
			<bean class="cn.itcast.ssm.Interceptor.MHandlerInterceptor" />
		</mvc:interceptor>
	</mvc:interceptors>

2.拦截器实现类

public class MHandlerInterceptor extends HandlerInterceptorAdapter  {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, accept, content-type, xxxx");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        response.setHeader("Access-Control-Allow-Origin", "*");  
        System.out.println("我真的执行了");
        return true;
    }
}

3.controller层

@Controller
public class UserController {
	@Autowired
	private UserMapper userMapper;
	
	@RequestMapping(value="/getUser")
	public @ResponseBody
	User findUser(){
		System.out.println("~~~~~~~~~~~~");
		User user1 = userMapper.findUserById(1);
		return user1;
	}
}

4.配置 vue项目中config/index.js文件(生成)

    proxyTable: {
         '/api': {
            // target:'http://ad.ydh123.com/f',
            target: 'http://10.0.1.60:8080/ning/',//设置你调用的接口域名和端口号 别忘了加http
            changeOrigin: true,//我发现这个不加也可以
            pathRewrite: {
              '^/api': '/'//这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add’即可
            }
          }
    },

5.main.js配置axios

import axios from 'axios';

axios.defaults.withCredentials = true;
Vue.prototype.$axios = axios

6.组件中发送请求

     getSwiperList(){
        this.$axios
          .post("/api/getUser.action",{},{
          })
          .then((response)=> {
              console.log(response)
          }).catch((error)=>{
          console.log(error);
        });
      },

猜你喜欢

转载自blog.csdn.net/aoxue018/article/details/82591120