一般我们解决跨域的问题分三种情况
前端解决:代理服务器
后端解决:cors
前端+后端:jsonp
下面我们就来说说如何用jsonp解决
jsonp的实现原理
通过利用动态创建script标签的src属性来实现访问数据的,因为src是不存在跨域的
注意:jsonp只能发送get请求,发送的不是ajax请求,是单独的请求方式
前端需要做的就是传一个函数的参数,接收返回的数据就是在函数里面接收
后端需要做的就是接收传过来的参数,然后返回函数的调用里面传需要返回的数据,注意返回的数据必须是字符串形式的
代码如下
前端的代码:需要在路径后面传一个为函数的参数,函数要写在路径前面
<!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>Document</title>
</head>
<body>
<script>
function fn(e){
console.log(e,'fn');
}
</script>
<script src="http://192.168.137.1:2000/list?fn=fn"></script>
</body>
</html>
后端的代码:注意返回的是fn(arr),arr必须转为字符串形式的返回
const express=require('express')
const app=express()
const arr = [{
id:2,name:'jack'
}]
app.get('/list',(req,res)=>{
console.log(req);
const fn = req.query.fn
res.send(fn+`(${JSON.stringify(arr)})`)
})
app.listen(2000,'192.168.137.1',()=>{
console.log('http://192.168.137.1:2000');
})