同源策略与跨域
同源:协议、域名、端口号 必须完全相同。
违背同源策略就是跨域。
例如:
协议:http或者是https
域名:www.xxx.com
端口号:80,8000等。
同源:同一个来源。
同源:可以直接简写服务器页面的地址。
先创建一个服务器。
// 创建并启动服务器---------------------------------------
const express = require('express');
const app = express();
app.listen(80, function () {console.log('服务器已启动,地址:127.0.0.1');
});// 127.0.0.1/home
app.get('/home', function (req, res) {// 响应一个页面res.sendFile(__dirname + '/23--同源.html');
});app.get('/data', function (req, res) {// 响应一个页面res.send('我是服务器的数据');
});
<!DOCTYPE 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>Document</title><script src="https://cdn.staticfile.org/axios/1.3.5/axios.min.js"></script>
</head><body><h1>我是同源页面</h1><button>点击获取服务器数据</button><script>document.querySelector("button").addEventListener("click", () => {axios({type: 'get',// 因为是这个页面和服务器所处的端口是同源的,故可简写地址url: '/data'}).then(function (res) {console.log(res.data);});});</script>
</body></html>
如何解决跨域?
1、jsonp,只支持get操作
JSONP 怎么工作的?
在网页有一些标签天生具有跨域能力,比如: img link iframe script.
JSONP 就是利用 script 标签的跨域能力来发送请求的。
2、设置CORS响应头实现跨域
CORS(Cross-Origin Resource Sharing),跨域资源共享。CORS 是官方的跨域解决方案,它的特点是不需要在客户端做任何特殊的操作
,完全在服务器中进行处理,支持get 和 post 请求。跨域资源共享标准新增了一组 HTTP 首部字段,允许服务器声明哪些源站通过浏览器有权限访问哪些资源。
CORS 怎么工作的?
CORS 是通过设置一个响应头来告诉浏览器,该请求允许跨域,浏览器收到该响应。
首先是创建并启动服务器
const express = require('express');
const app = express();app.listen(80, () => {console.log('express server running at http://127.0.0.1:80');
});app.get('/cors-server', (req, res) => {res.send('hello cors!');
});
<!DOCTYPE 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>Document</title>
</head><body><button>发送请求</button><div></div><script>const btn = document.querySelector('button');btn.addEventListener('click', () => {// 1.创建对象const xhr = new XMLHttpRequest();// 2.初始化设置xhr.open('GET', 'http://127.0.0.1:80/cors-server');// 3.发送xhr.send();// 4.绑定事件xhr.onreadystatechange = function () {if (xhr.readyState === 4) {if (xhr.status >= 200 && xhr.status <= 300) {console.log(xhr.response);document.querySelector('div').innerHTML = xhr.response;}}}});</script>
</body></html>
错误提示是所请求的资源上没有cess-Control-Allow-Origin'
这个标头。
那在服务器端加上这个标头就可以了。
app.get('/cors-server', (req, res) => {// * 表示所有的网站都可以访问res.setHeader('Access-Control-Allow-Origin', '*');// 表示:只有这个http:127.0.0.1:500/cors-server可以访问。 这个会覆盖上面的// res.setHeader('Access-Control-Allow-Origin', 'http:127.0.0.1:500');res.send('hello cors!');
});