关于cors:一篇搞定面试中的跨域问题
什么是CORS(跨源资源共享)?CORS(Cross-Origin Resource Sharing)是一种机制,容许网页从不同的域拜访服务器上的资源。 在同源策略下,浏览器限度了跨域拜访,CORS容许服务器指定哪些源能够拜访其资源。 同源策略(Same-origin policy)同源策略在web利用平安模型中是一个重要的概念。在这个策略下,浏览器容许第一个网页中蕴含的脚本能够获取第二个网页的数据,前提是这两个网页在同一个源下。 同源:须要URI、主机名、端口都雷同。 这个策略能够避免一个网页上的歹意脚本通过DOM获取其余网页的敏感数据。 须要牢记的一点就是同源策略只利用于脚本,这意味着像images、css和其余动静加载的脚本 能够通过对应的标签跨域拜访资源。 是否同源的规定同源须要满足雷同的协定(scheme),雷同的主机名(host),雷同的端口号(port) Compared URLOutcome Reasonhttp://www.example.com/dir/page2.htmlSuccess Same scheme, host and porthttp://www.example.com/dir2/other.htmlSuccess Same scheme, host and porthttp://username:password@www.example.com/dir2/other.htmlSuccess Same scheme, host and porthttp://www.example.com:81/dir/other.htmlFailure Same scheme and host but different porthttps://www.example.com/dir/other.htmlFailure Different schemehttp://en.example.com/dir/other.htmlFailure Different hosthttp://example.com/dir/other.htmlFailure Different host (exact match required)http://v2.www.example.com/dir/other.htmlFailure Different host (exact match required)http://www.example.com:80/dir/other.htmlDepends Port explicit. Depends on implementation in browser.::: tipscheme: http https::: CORS存在的意义跨域资源共享(CORS) 是一种机制,它应用额定的 HTTP 头来通知浏览器 让运行在一个 origin (domain) 上的Web利用被准许拜访来自不同源服务器上的指定的资源。 出于安全性,浏览器限度脚本内发动的跨源HTTP申请。 例如,XMLHttpRequest 和 Fetch API 遵循同源策略。这意味着应用这些 API 的 Web 应用程序只能从加载应用程序的同一个域申请 HTTP 资源,除非响应报文蕴含了正确 CORS 响应头。 ...