同源: 协议,域名,端口号必须相同
违背同源策略就是跨域
index.html
<!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>
<h1>123213</h1>
<button>点击获取</button>
<script>
const btn = document.querySelector('button');
btn.onclick = function(){
const x = new XMLHttpRequest();
//因为这里是同源策略,所以url可以简写。
x.open("GET",'/data')
//发送
x.send();
//
x.onreadystatechange = function(){
if(x.readyState === 4){
if(x.status >= 200 && x.status < 300){
console.log(x.response);
}
}
}
}
</script>
</body>
</html>
server.js
const express = require('express');
const app = express();
app.get('/home',(request,response)=>{
response.sendFile(__dirname + '/index.html'); //dirname绝对路径
});
app.get('/data',(request, response) => {
response.send('用户数据');
})
app.listen(9000, () => {
console.log("服务已经启动");
})
注意:此处需要从127.0.0.1:9000启动程序,否则不发获取数据。