大庆做网站公司,html网站中文模板下载,淘宝客推广网站模板,百度快照优化的优势是什么简介
出于安全方面考虑#xff0c;浏览器发起请求时#xff0c;会先检查同源策略#xff08;协议、主机、端口是否与当前页面相同#xff09;#xff0c;不匹配则认为是跨域请求。
CORS (Cross-Origin Resource Sharing)
CORS是一种机制#xff0c;允许服务器声明哪些…简介
出于安全方面考虑浏览器发起请求时会先检查同源策略协议、主机、端口是否与当前页面相同不匹配则认为是跨域请求。
CORS (Cross-Origin Resource Sharing)
CORS是一种机制允许服务器声明哪些域origin可以访问其资源从而绕过同源策略的限制。浏览器会发送预检请求Preflight Request以确定是否允许跨域访问。
Preflight请求
Preflight请求是跨域资源共享CORS中的一种机制用于在实际请求之前发送一个预检请求。浏览器在发送某些类型的跨域请求例如带有自定义标头的请求之前会自动发送一个OPTIONS请求以获取目标服务器是否允许实际请求的权限。
预检请求包含一组查询信息询问服务器是否允许实际请求。这些查询信息包括
Access-Control-Request-Method 表示实际请求中将使用的 HTTP 方法例如 GET、POST。Access-Control-Request-Headers 表示实际请求中将使用的自定义 HTTP 标头。
服务器收到预检请求后会检查这些信息然后决定是否允许实际请求。如果服务器允许它会在响应中包含相应的 CORS 头例如 Access-Control-Allow-Origin、Access-Control-Allow-Methods 等。
这个预检请求机制有助于确保安全因为它防止了潜在的恶意跨域请求。如果服务器支持并验证了预检请求浏览器才会允许实际请求。
以下是一个预检请求的示例
请求
OPTIONS /example/resource HTTP/1.1
Host: example.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type, Authorization响应
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://example.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Content-Type, AuthorizationSpring MVC跨域设置
浏览器发起Preflight请求SpringMVC的处理流程为 DispatcherServlet#doDispatch - HttpRequestHandlerAdapter#handle - AbstractHandlerMapping#handleRequest - DefaultCorsProcessor#processRequest DefaultCorsProcessor会根据当前配置的跨域规则检查当前资源你是否允许发起的域访问检查不通过时直接返回403 Forbiddenbody为Invalid CORS request。
注解方式 可以在类或者方法上使用CrossOrigin(origins *, methods {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
Filter模式 对于使用了Spring-Web而没有使用SpringMVC的项目可以使用Spring提供的CorsFilter它会拦截的Servlet请求并添加一些允许跨域的头以下是允许所有请求跨域的示例
Configuration
public class CorsConfig {Beanpublic CorsFilter corsFilter() {UrlBasedCorsConfigurationSource source new UrlBasedCorsConfigurationSource();CorsConfiguration config new CorsConfiguration();config.addAllowedOrigin(*);config.addAllowedMethod(*);config.addAllowedHeader(*);source.registerCorsConfiguration(/**, config);return new CorsFilter(source);}
}测试
可以使用以下html进行跨域测试
!DOCTYPE html
html langen
headmeta charsetUTF-8meta nameviewport contentwidthdevice-width, initial-scale1.0titlePOST Request Form/title
/head
bodyh1POST Request Form/h1form idpostFormlabel forurlURL:/labelinput typetext idurl nameurl valuehttp://xxx stylewidth: 100%; margin-bottom: 10px;label forpostDataPOST Data:/labeltextarea idpostData namepostData stylewidth: 100%; height: 100px; margin-bottom: 10px;
{}/textareabutton typebutton onclicksendPostRequest()Send POST Request/button
/formscript
function sendPostRequest() {var url document.getElementById(url).value;var postData document.getElementById(postData).value;fetch(url, {method: POST,headers: {Content-Type: application/json,},body: postData,}).then(response response.json()).then(data {console.log(Success:, data);alert(POST request sent successfully!);}).catch((error) {console.error(Error:, error);alert(Error sending POST request!);});
}
/script/body
/html