关于请求跨域及response中Set-Cookie无效问题记录
来源:互联网 发布:书生商友seo 编辑:程序博客网 时间:2024/05/29 12:30
最近开发一个项目,项目前后端完全分离,即
页面放在192.168.0.105:8080中,
服务端放在192.168.0.105:57500中,
这样前台发送请求后会出现跨域问题,针对跨域问题,解决思路为处理响应头,步骤如下
1.定义一个过滤器,在web.xml中配置
<filter> <filter-name>ajaxFilter</filter-name> <filter-class>com.tbms.filter.AjaxFilter</filter-class><!-- 自定义过滤器 --> </filter> <filter-mapping> <filter-name>ajaxFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2.在过滤其中处理响应头
public class AjaxFilter extends OncePerRequestFilter{@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)throws ServletException, IOException {System.out.println("拦截到了" + request.getRequestURL());response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since");response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");response.setHeader("Access-Control-Max-Age", "3600");response.addHeader("Access-Control-Allow-Credentials", "true");response.setCharacterEncoding("UTF-8");response.setContentType("application/json");//此行代码确保请求可以继续执行至ControllerfilterChain.doFilter(request, response); }}3.前台发送请求
$.ajax({type: "post",url: that.ip + that.port + that.prjName + "/login",data: JSON.stringify(loginInfo),contentType: "application/json",dataType: "json",xhrFields: {withCredentials: true},success: function(rs) {if(rs.state == 'success'){that.SelectCompany = false;that.$router.push("/index/res/signet")}},error: function(){alert("用户名密码错误!");},});
PS:1.第二步中红色代码"Access-Control-Allow-Origin"对应的值不能为通配符“*”。2.response.addHeader("Access-Control-Allow-Credentials", "true");该行代码表示允许跨域发送Cookie
3.在ajax请求中应加入xhrFields: {withCredentials: true},否则,依然不会发送Cookie
阅读全文
0 0
- 关于请求跨域及response中Set-Cookie无效问题记录
- response.addCookie(cookie)无效
- 关于Cookie跨域操作遇到的问题及解决方法
- 关于Cookie跨域操作遇到的问题及解决方法
- ajax跨域请求及传递cookie
- ajax跨域请求及传递cookie
- JAVAWeb中请求Request,Response,cookie的中文乱码处理
- 关于 S40 Http set-cookie的问题
- ajax请求中session无效的问题
- 关于Android连接request和response中携带cookie
- 关于 Set-Cookie 字段
- 【分享】记一次前端跨域请求后台无法set-cookie经历
- 关于HttpWebResponse里拿不到Set-Cookie的问题
- 关于python 的django-forbidden-csrf-cookie-not-set问题
- 解决Android Http请求处理Response Cookie时区加载过慢问题
- 关于Cookie跨域的问题
- 关于Cookie跨域的问题
- 关于Cookie跨域的问题
- 利用mvc 和数据结合来做mail 邮件系统
- Leetcode——第21题
- 51nod1483-技巧&标记&思维-化学变换
- mark
- 新手村 循环 三连击
- 关于请求跨域及response中Set-Cookie无效问题记录
- mybatis中﹤![CDATA[ ]]> 的使用
- 10.7日常总结
- JS判断文件大小是否上传
- RESTful 架构详解
- DoG (Difference of Gaussian)角点检测
- Shell中的${}、##和%%使用范例
- hdu 4800 Josephina and RPG (概率dp)
- 零基础入门深度学习!!!