大佬们🤞谈谈你们对浏览器跨域的理解

108 阅读3分钟

跨域-素材准备及错误展示

目录结果

根目录
├── public
│   ├── js
    		└── axios.js
│   └── index.html  # 提前准备好的页面
└── server.js

前端页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <button id="btn1_get">接口测试1:get请求带参数</button>
    <button id="btn2_post"> 接口测试2:post-传递普通键值对</button>
    <hr/>
    <button id="btn3_postJSON">接口测试3:post-传递json</button>
    <hr/>
    <form id="myform">
        <input type="text" name="title">
        <input type="file" name="cover">
    </form>
    <button id="btn4_formdata">接口测试4:post-传递formdata</button>
    <hr/>
    <script src="./js/axios.js"></script>
    <script>
    document.getElementById('btn1_get').addEventListener('click',() => {
        axios.get('http://localhost:3000/getapi', {params: {a:1,b:2}})
    })
    var obj = {
        "name":"abc",
        "address":{
            "a":1,
            "b":2,
            "info":"c"
        }
    }
    document.getElementById('btn2_post').addEventListener('click', () => {
        const params = new URLSearchParams();
        params.append('param1', 'value1');
        params.append('param2', 'value2');
        axios.post('http://localhost:3000/post', params, {
            headers: {"content-type":"application/x-www-form-urlencoded"}})
    })

    document.getElementById('btn3_postJSON').addEventListener('click', () => {
        axios.post('http://localhost:3000/postJSON', obj)
    })

    document.getElementById('btn4_formdata').addEventListener('click', () => {
        console.log(1)
        var fd = new FormData(document.getElementById('myform'));

        axios.post('http://localhost:3000/publish', 
            fd
        )
    })
    </script>
</body>
</html>

后端

// 实现get接口
const express = require('express')
const app = express();

app.use(express.static('public'))
// 引入bodyParse包
const bodyParser = require('body-parser')
// 使用包. 则在后续的post请求中
// 会自动加入req.body属性,这个属性中就包含了post请求所传入的参数
// 处理普通的键值对格式
// Content-Type: application/x-www-form-urlencoded
app.use(express.urlencoded())

// 处理JSON格式
// Content-Type: application/json;
app.use(express.json())

// 引入multer包
const multer = require('multer');

// 配置一下multer
// 如果本次post请求涉及文件上传,则上传到uploads这个文件夹下
// Content-Type: multipart/form-data;
var upload = multer({ dest: 'uploads/'})


// 实现接口1: get类型接口
// 返回所传入的参数,并附上上时间戳
app.get('/getapi',(req,res)=>{
    // 通过 req.query快速获取传入的参数
    console.log(req.query);
    let obj = req.query
    
    obj._t = Date.now(); 
    res.json( obj )
})

// 实现接口2:普通post 键值对
app.post('/post',(req,res)=>{
    // 希望在后端收到post传参
    console.log(req.body);

    let obj = req.body
    obj._t = Date.now();
    
    res.json(obj)
})

// 实现接口3:用来JSON格式的数据
// Content-Type: application/json;
app.post('/postJSON',(req,res)=>{
    // 希望在后端收到post传参
    console.log(req.body);
    
    // res.send('/postJSON')
    res.json( req.body )
})

// 实现接口4:接口formDate
app.post('/publish',upload.single('cover'),(req,res)=>{
    console.log('publish...')
    //upload.single('cover')
    // 这里的cover就是在页面中表单元素中的name
    // <input type="file" name="cover" />
    // 把要上传文件放在指定的目录
    console.log(req.file);
    // 其它参数,还是在req.body中找
    console.log(req.body);

    res.json({code:200,msg:'上传成功',info:req.file.path})
})

app.listen(3000,()=>{
    console.log('express应用在3000端口启动了'); 
})

问题演示

image.png

把前端代码单独运行,就会报错

image (1).png

这是跨域错误的说明

什么导致了浏览器报跨域或错误

发送ajax请求的那个页面的地址和ajax接口地址 不在同一个域中

跨域错误: 不同源的ajax请求 ===>报跨域的错误

浏览器向web服务器发起http请求时,如果同时满足以下三个条件时,就会出现跨域问题,从而导致ajax请求失败

(1)请求响应双方url不同源

对方url:发出请求所在的页面 与 所请求的资源的url

同源是指 协议相同,域名相同,端口相同 都相同

以下不同源的

http://127.0.0.1:5500/message_front/index.html 请求http://localhost:8080/getmsg

网路中不同源的请求很多

(2)请求类型是xhr请求,就是常说ajax请求,不是请求图片路径资源,js文件,css等

(3)浏览器觉得不安全,跨域问题出现的基本原因是浏览器同源策略是一个安全策略,

它限制一个origin的文段或者加载的脚本如何能与另外一个资源,只是返回到浏览器

image (1).png 端的出错

CoRs

CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。

CORS需要浏览器和服务器同时支持。目前,所有浏览器都支持该功能,IE浏览器不能低于IE10(ie8通过XDomainRequest能支持CORS)。

跨域错误说明

image.png

1手写在被请求的路由设置header头,可以实现跨域

app.get('/get', (req, res) => {
  // * 表示允许任何域名来访问
  res.setHeader('Access-Control-Allow-Origin', '*')
  // 允许指定源访问
  // res.setHeader('Access-Control-Allow-Origin', 'http://www.xxx.com')
  res.send(Date.now().toString())
})
})
  • 这种方案无需客户端作出任何变化(客户端不用改代码),就当跨域问题不存在一样。
  • 服务端响应的时候添加一个 Access-Control-Allow-Origin 的响应头

2使用cors

要点

1 它是一个npm包,要单独下载使用npm包cors

npi i cors

2当做exepress中的中间件,但是要注意哦代码应该放在顶部


var cors = require('cors')
app.use(cors())