• Ajax学习:同源策略(与跨域相关)ajax默认遵循同源策略


    同源策略:是浏览器的一种安全策略

    同源意味着:协议、域名、端口号必须相同

    违背同源便是跨域


    当前网页的url和ajax请求的目标资源的url必须协议、域名、端口号必须相同

    比如:当前网页:协议http 域名 a.com  端口号8000

                目标请求:协议http 域名 a.com  端口号8000


    同源表示:同一个来源

    如果 a.com -->b.com发请求是跨域

            http---->https发请求是跨域

            800--->799发请求是跨域

     性能是有限的,服务器增加,所以便会出现跨域


     服务器部分:
     

    1. const express=require('express')
    2. const app=express();
    3. app.get('/home',function(requset,response){
    4. //设置响应头 名称 值----设置允许跨域
    5. // response.setHeader('Access-Control-Allow-Origin','*');
    6. //设置响应体
    7. response.sendFile(__dirname+'/同源策略.html');//绝对路径
    8. })
    9. app.get('/data',function(requset,response){
    10. //设置响应头 名称 值----设置允许跨域
    11. // response.setHeader('Access-Control-Allow-Origin','*');
    12. //设置响应体
    13. response.send('用户数据');//绝对路径
    14. })
    15. app.listen(9000,()=>{
    16. console.log('9000启动成功')
    17. })

     前端部分

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>Documenttitle>
    8. head>
    9. <body>
    10. <h2>主页面h2>
    11. <button>点击获取用户数据button>
    12. <script>
    13. const btn=document.querySelector('button');
    14. btn.onclick=function() {
    15. const xhr=new XMLHttpRequest();
    16. //因为满足同源策略,所以url可以简写
    17. //浏览器回自动加上
    18. xhr.open('GET','/data');
    19. xhr.send();
    20. xhr.onreadystatechange=function(){
    21. if(xhr.readyState===4){
    22. if(xhr.status<300&&xhr.status>=200){
    23. console.log(xhr.response)
    24. }
    25. }
    26. }
    27. }
    28. script>
    29. body>
    30. html>

    使用url与服务器响应信息(是同源的),再网页中button发送是ajax请求(由于当前网页与按钮访问的协议 域名端口都一致 满足同源策略 所以可以省略url部分)

     

  • 相关阅读:
    Golang | Leetcode Golang题解之第50题Pow(x,n)
    Salesforce-Visualforce-6.静态资源(Static Resources)
    shell脚本之文件读写
    opencv-图像平滑
    一种基于非线性惯性权重的海鸥优化算法-附代码
    Ubuntu18.4 搭建pytorch编译环境
    驱动开发:通过MDL映射实现多次通信
    AHU 汇编 实验二
    MATLAB算法实战应用案例精讲-【深度学习】BP神经网络
    vue后台开发第一步
  • 原文地址:https://blog.csdn.net/weixin_47295886/article/details/128142620