相关文章推荐
深情的煎鸡蛋  ·  the value of the ...·  2 周前    · 
求醉的剪刀  ·  stata xtile函数 - CSDN文库·  5 月前    · 
失眠的围巾  ·  Python: How to write ...·  1 年前    · 

1.出现跨域问题

当我们在前端项目中,向后端发送请求的获取课程数据的时候,出现了跨域问题:

  • 已被CORS策略阻止:请求的资源上没有' Access-Control-Allow-Origin'标头(跨域请求失败)

报错示例:

Access to XMLHttpRequest at 'http://localhost:8080/demo/getUserList' from origin 'http://localhost:8088' has been blocked by CORS policy: No ' Access-Control-Allow-Origin ' header is present on the requested resource.

在运行前端项目的时候,F12 调试,看console的打印,看到“ Access-Control-Allow-Origin ”这个关键信息,就说明是跨域问题了。

2. 什么是跨域

那什么是跨域呢?

跨域是指通过JS在不同的域之间进行数据传输或通信,比如用ajax向一个不同的域请求数据,只要 协议 域名 端口 有任何一个不同,都被当作是不同的域,浏览器就不允许跨域请求。

  • 跨域的几种常见情况:

3.解决跨域问题

跨域的允许主要由服务器端控制。服务器端通过在响应的 header 中设置 Access-Control-Allow-Origin 及相关一系列参数,提供跨域访问的允许策略

  • 设置响应头中的参数来允许跨域域请求:
  • Access-Control-Allow-Credentials

Access-Control-Allow-Origin 标识允许跨域的请求有哪些

1. 在POM.xml 文件中引入依赖

<!-- 解决跨域问题所需依赖 -->
<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>cors-filter</artifactId>
    <version>2.5</version>
</dependency>

2. 在web.xml中 配置跨域 filter

<!--配置跨域过滤器-->
<filter>
    <filter-name>corsFilter</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>corsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

再次查询,解决跨域问题之后,页面显示数据。

出现此问题的原因是 所请求的资源上没有“ Access - Control - Allow - Origin ”标头。 这个是域名的问题,比如你本地域名跟测试站域名冲突,因为在代码中已经设置成某个固定的域名了,所以请求接口的时候本地无法访问到测试站域名,所以要找到config文件最初配置域名的地方把他改成本地的域名就可以了 了。 解决 跨域问题 也很简单,在PHP代码中增加头部即可。 $ header [' Access - Control - Allow - Origin '] = '*'; $ header [' Access -Contr
No ' Access - Control - Allow - Origin ' header is present on the requested resource.'Ajax 跨域 访问 解决 方案
Access - Control - Allow - Origin 是一个HTTP头部字段,它允许服务器指定哪些源(通常是指域名或URL)可以访问其资源。当浏览器发起 跨域 请求时,如果服务器返回这个头信息,并设置了允许特定的来源(如"*"表示所有来源),那么 前端 JavaScript就能从该来源接收响应。 简单 跨域 请求(CORS)默认只允许同源策略下的请求,即请求的协议、域名和端口必须完全一致。为了处理这种限制,开发者需要在服务端设置 Access - Control - Allow - Origin ,告诉浏览器允许其他域的请求。 例如,在Node.js的Express应用中,你可以这样做: ```javascript app.options('*', function(req, res) { res. header (' Access - Control - Allow - Origin ', '*'); res. header (' Access - Control - Allow -Methods', 'GET, POST, PUT, DELETE'); res. header (' Access - Control - Allow - Header s', 'Content-Type'); res.status(204).send(); app.get('/api/data', function(req, res) { // 设置允许的来源 res. header (' Access - Control - Allow - Origin ', req. header s. origin ); res.send(data);