0
点赞
收藏
分享

微信扫一扫

什么是同源策略以及同源策略的案例

玉字璧 2022-04-14 阅读 106
ajax
  • 同源策略:当前的网页的url和ajax请求的目标资源的url两者之间必须满足:协议、域名、端口号 完全相同
  • 违背同源策略就是跨域
  • ajax默认是遵循同源策略的

同源策略小案例

<h1>首页</h1>
<button>点击获取用户数据</button>
const btn = document.querySelector("button");
btn.onclick = function () {
    // 创建对象
    const xhr = new XMLHttpRequest();
    // 初始化 设置请求的方法和url
    // 因为这里是满足同源策略的 url可以简写
    xhr.open('GET', '/data');
    // 发送
    xhr.send();
    // 绑定事件
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                console.log(xhr.response);
            }
        }
    }
}
// server.js
// 1. 引入express
const express = require('express');
// 2. 创建应用对象
const app = express();
// 3. 创建路由规则
app.get('/home', (request, response) => {
    // __dirname 表示当前文件的绝对路径
    response.sendFile(__dirname + '/index.html');
});

app.get('/data', (request, response) => {
    response.send('用户数据');
})
// 4. 监听端口启动服务
app.listen(9000, () => {
    console.log("服务已启动,9000端口监听中......");
})
举报

相关推荐

同源策略

同源策略讲解

同源策略浅析

同源策略与Jsonp

【同源策略】基础内容

浏览器同源策略

0 条评论