微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

十二、Ajax同源策略

http://127.0.0.1:8000/home

<!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>首页</title>
</head>
<body>
    <h1>百度</h1>
    <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 >= 200 && xhr.status < 300){
                        console.log(xhr.response);
                    }
                }
            }
        }
    </script>
</body>
</html>
//引入express
const express = require('express');

//创建应用对象
const app = express();

//同源策略
app.get('/home',(request,response)=>{
    //响应页面
    response.sendFile(__dirname+'/Test.html');
});

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐