同源策略:是浏览器的一种安全策略
同源意味着:协议、域名、端口号必须相同
违背同源便是跨域
当前网页的url和ajax请求的目标资源的url必须协议、域名、端口号必须相同
比如:当前网页:协议http 域名 a.com 端口号8000
目标请求:协议http 域名 a.com 端口号8000
同源表示:同一个来源
如果 a.com -->b.com发请求是跨域
http---->https发请求是跨域
800--->799发请求是跨域
性能是有限的,服务器增加,所以便会出现跨域
服务器部分:
- const express=require('express')
-
- const app=express();
- app.get('/home',function(requset,response){
- //设置响应头 名称 值----设置允许跨域
- // response.setHeader('Access-Control-Allow-Origin','*');
- //设置响应体
- response.sendFile(__dirname+'/同源策略.html');//绝对路径
- })
- app.get('/data',function(requset,response){
- //设置响应头 名称 值----设置允许跨域
- // response.setHeader('Access-Control-Allow-Origin','*');
- //设置响应体
- response.send('用户数据');//绝对路径
- })
- app.listen(9000,()=>{
- console.log('9000启动成功')
- })
前端部分
- 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>
- head>
- <body>
- <h2>主页面h2>
- <button>点击获取用户数据button>
- <script>
- const btn=document.querySelector('button');
- btn.onclick=function() {
- const xhr=new XMLHttpRequest();
- //因为满足同源策略,所以url可以简写
- //浏览器回自动加上
- xhr.open('GET','/data');
- xhr.send();
- xhr.onreadystatechange=function(){
- if(xhr.readyState===4){
- if(xhr.status<300&&xhr.status>=200){
- console.log(xhr.response)
- }
- }
- }
-
- }
- script>
- body>
- html>
使用url与服务器响应信息(是同源的),再网页中button发送是ajax请求(由于当前网页与按钮访问的协议 域名端口都一致 满足同源策略 所以可以省略url部分)
