跨域的解决方案 希望能帮到你们哦

832 阅读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.png

是什么原因导致跨域问题呢

发送ajax请求的那个页面的地址和 ajax的接口地址 是不在一个域中
不同源的ajax请求 就是跨域错误
请求是可以发送到后端的,后端也能正常处理,但是当它返回结果的时候,却发现它本次请求是跨域,所以报错了。

image.png

解决方案 有两种

一种是用JSONP解决,一种是用CORS解决。

1.改发JSONP

JSON with Padding,是一种借助于 script 标签发送跨域请求的技巧。它本质并不是ajax请求,所以没有跨域问题。

原理

  • script的src属性可以请求外部的js文件,这个不是ajax请求,所以没有跨域问题
  • 我们可以借助script标签上的src属性用于请求服务端的接口。<script src="http://localhost:3000/get"
  • 服务器的接口返回JavaScript脚本,并且附上需要返回的数据。例如:res.end("fn(数据)")

看图理解

image.png

实现步骤

让script标签的src指向接口地址

<html>
    <script src="http://localhost:3000/get"></script>
</html>

改造接口,返回函数调用表达式,并传入数据

const express = require('express');

const app = express();

app.get('/get', (req, res) => {
  const data =  JSON.stringify({a:1,b:2})
  const fnStr = `fn(${data})`
  res.end(fnStr); // 返回字符串,内容是:函数调用语句
})

app.listen(3000, () => {
  console.log('你可以通过http://localhost:3000来访问...');
});

在前端准备相应的函数

这里需要提前定义一个函数,必须在引入接口地址的上面 才能实现功能

<script>
    function fn(rs) {
        console.log(rs);
    }
</script>
<html>
    <script src="http://localhost:3000/get"></script>
</html>

看图理解

image.png

2.CORS简介

CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。 ORS需要浏览器和服务器同时支持。目前,所有浏览器都支持该功能,IE浏览器不能低于IE10(ie8通过XDomainRequest能支持CORS)。

下载cors包

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

使用cors包

当做express中的中间件,注意代码应该放在顶部

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

jsonp vs cors 对比

jsonp:

  • 不是ajax
  • 只能支持get方式
  • 兼容性好

cors:

  • 前端不需要做额外的修改,就当跨域问题不存在。
  • 是ajax
  • 支持各种方式的请求(post,get....)
  • 浏览器的支持不好(标准浏览器都支持)

以上就是我的解决方案,两种都可以,看你喜欢用哪个就用哪个解决就好