【问题描述】跨域请求:CORS 头缺少 ‘Access-Control-Allow-Origin’

it2023-08-12  67

Ajax 同源 与 异域问题

问题场景: 在编写好了前后端程序之后,连接服务器的过程中出了错,浏览器显示如下: 已拦截跨源请求:同源策略禁止读取位于 http://localhost:9955/dbUserController/login?username=zhangsan&pwd=lisi 的远程资源。(原因:CORS 头缺少 ‘Access-Control-Allow-Origin’)。 原后端代码如下: @RequestMapping(value="/login" , method = RequestMethod.GET) public String Login(HttpServletRequest request){ String username = request.getParameter("username"); String pwd = request.getParameter("pwd"); //……………… }
问题产生的原因:

在连接前后端的时候,没有对应好每一个端口与地址,所以产生了同源问题

解决方案:

方案 1:找出所有的端口并对齐

方案 2:在服务器的Controller层添加如下代码(展示添加后的效果):

@RequestMapping(value="/login" , method = RequestMethod.GET) public String Login(HttpServletRequest request, HttpServletResponse response){ response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Cache-Control","no-cache"); String username = request.getParameter("username"); String pwd = request.getParameter("pwd"); //...... }

最后登陆成功: 如果还有更好的,欢迎留言讨论或者教教我这个小老弟。

最新回复(0)