CROS:跨域资源共享、是官方的跨域解决方案,特点不需要在客户端做任何特殊的操作,完全在服务器中处理(支持get post 等)
客户端做ajax请求,服务端做相应头设置就可以实现跨域:
- html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Documenttitle>
- <style>
- #result {
- width: 200px;
- height: 100px;
- border: 1px slateblue solid;
- }
- style>
- head>
- <body>
- <button>发送请求button>
- <div id="result">div>
- <script>
- const btn =document.querySelector('button');
- const result=document.querySelector('div')
- btn.addEventListener('click', function() {
-
- //4步骤走
- const xhr = new XMLHttpRequest();
- xhr.open('GET', 'http://127.0.0.1:9000/cors-server');
- xhr.send();
- xhr.onreadystatechange = function() {
- if (xhr.readyState === 4) {
- if (xhr.status < 300 && xhr.status >= 200) {
- console.log(xhr.response)
- }
- }
- }
- })
- script>
- body>
- html>
- const {
- json
- } = require('express');
- const express = require('express')
-
- const app = express();
-
-
- app.all('/cors-server',function(requset,response){
- response.send('CORS 跨域请求')
- })
-
- app.listen(9000, () => {
- console.log('9000启动成功')
- })
Access to XMLHttpRequest at 'http://127.0.0.1:9000/cors-server' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
被CORS 跨域共享机制阻止 服务端没有Access-Control-Allow-Origin响应头
要想实现跨域请求,必须在服务端返回结果的时候设置响应头
file协议向http 发送请求 Access-Control-Allow-Origin 后面填写运行网页的url *是通配所有网页

http和http不需要

实际上有一组响应头
跨源资源共享(CORS) - HTTP | MDN (mozilla.org)
Access-Control-Allow-Origin 参数指定了单一的源(什么客户端的url可以访问该资源),
Access-Control-Expose-Headers:暴露头部信息,客户端同意的哪些头可以暴露
Access-Control-Max-Age:预请求结果缓存。加一个时间,每次请求就会在规定时间有效,超过使时间不会预检
Access-Control-Allow-Credentials: 跨域请求时候,是否允许携带验证信息(cookie)
Access-Control-Allow-Methods:设置请求允许的方法
Access-Control-Allow-Headers:设置头信息(自定义头不允许 所以需要在响应前接收的任意请求头)
- app.all('/cors-server', function(requset, response) {
- response.setHeader('Access-Control-Allow-Origin', '*');
- response.setHeader('Access-Control-Allow-Headers', '*'); //头,方法
- response.setHeader('Access-Control-Allow-Methods', '*')
- response.send('CORS 跨域请求')
- })