浏览器之跨域问题

1.  跨域问题

    只发生在浏览器里的JavaScript,试图去读取另一个源的响应数据时。

    重点三个词:

      浏览器

      JavaScript

      读取响应

2.  同源

    协议http/https  一致

    域名或IP  一致

    端口  一致

    只要有一个不同,就会发生跨域

3.  一定会产生跨域问题的情况

    1.  AJAX/fetch/axios跨源请求

        fetch('https://api.other.com/data')  向页面发送请求,并且读取响应内容        

    2.  JS读取跨源iframe内容

        <iframe src="https://other.com"></iframe>          

    3.  JS操作跨源windows

        const w = window.open('https://other.com');  打开新页面不跨域

        w.document // ❌  这个操作跨域

    4.  前端直连内网/IP

        fetch('http://192.168.1.10/api')    

4.  不会产生跨域问题的情况

    1.  浏览器地址栏跳转/打开新页面

        <a href="https://other.com">

        window.open(...)

        location.href = ...

        js不读取响应,所以不会跨域        

    2.  form表单直接提交

        <form action="https://other.com/upload" method="post">

        请求能发,JS拿不到返回,不触发CORS

    3.  后端服务之间互相调用

        永远不存在跨域,因为不是浏览器

    4.  curl/wget/Postman

        永远不存在跨域,因为不是浏览器

5.  表格速查

    image          

posted @ 2026-01-19 17:56  奋斗史  阅读(2)  评论(0)    收藏  举报