完美解决axios跨域请求出错的问题
错误信息:
Response to preflight request doesn't pass aess control check: No 'Aess-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed aess. The response had HTTP status code 403
随着前端框架的发展,如今前后端数据分离已经成了趋势,也就是说,前端只需要用ajax请求后端的数据合成页面,后端仅仅提供数据接口,给数据就行,好处就是前端程序员再也不用在自己的本地搭建Web服务器,前端也不需要懂后端语法,后端也不需要懂前端语法,那么简化了开发配置,也降低了合作难度。
常规的GET,POST,PUT,DELETE请求是简单请求(相对于OPTIONS请求),但是OPTIONS有点儿特别,它要先发送请求问问服务器,你要不要我请求呀,要我就要发送数据过来咯(这完全是根据自己的理解写的,如果有误,敬请谅解,请参考阮一峰大神原文。)
在Vue的项目里,Http服务采用Axios,而它正是采用OPTIONS请求。
如果仅仅在header里面加入: 'Aess-Control-Allow-Origin':*,是并不能解决问题的,错误就是如文章开头所示。
这儿就需要后台对OPTIONS请求额外处理。
本文以Spring MVC为例:
添加一个拦截器类:
public class ProcessInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { httpServletResponse.setHeader("Aess-Control-Allow-Origin", "*"); httpServletResponse.setHeader("Aess-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Aept,X-Requested-With"); httpServletResponse.setHeader("Aess-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); httpServletResponse.setHeader("X-Powered-By","Jetty"); String method= httpServletRequest.getMethod(); if (method.equals("OPTIONS")){ httpServletResponse.setStatus(200); return false; } System.out.println(method); return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
在spring-mvx.xml配置Spring 拦截器:
<mvc:interceptors> <bean class=".tfzc.ssm.mon.innterceptor.ProcessInterceptor"></bean> </mvc:interceptors>
至此,问题已经解决:
以上这篇完美解决axios跨域请求出错的问题就是长沙网络推广分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持狼蚁SEO。
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程