一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第14天,点击查看活动详情。
JSONP 的概念
浏览器端通过 <script> 标签的 src 属性,请求服务器上的数据,同时,服务器返回一个函数的调用,这种请求数据的方式叫做 JSONP
JSONP 的特点
- JSONP 不属于真正的 Ajax 请求,因为它没有使用 XMLHttpRequest 这个对象
- JSONP 仅支持 GET 请求,不支持 POST、PUT、DELETE 等请求
创建 JSONP 接口的注意事项
如果项目中已经配置了 cors 跨域资源共享,为了防止冲突,必须在配置 cors 中间件之前声明 JSONP 的接口,否则,JSONP 接口会被处理成开启了 cors 的接口
// 优先创建 JSONP 接口(这个接口不会被处理成 cors 接口)
app.get('/api/jsonp', (req, res)=>{
})
// 再配置 cors 中间件(后续所有接口,都会被处理成 cors 接口)
app.use(cors())
// 这是一个开启了 cors 的接口
app.get('api/get', (req, res)=>{
})
实现 JSONP 接口的步骤
- 获取客户端发送过来的回调函数的名字
- 得到要通过 JSONP 形式发送给客户端的数据
- 根据前两步得到的数据,拼接出一个函数调用的字符串
- 把上一步拼接得到的字符串,响应给客户端的
<script>标签进行解析执行
const express = require('express')
const app = express()
app.use(express.urlencoded({extended: false}))
app.get('/api/jsonp', (req, res) => {
// 得到函数的名称
const funcName = req.query.callback
// 定义要发送到客户端的数据对象
const data = {name:'lilei', age:18}
// 拼接出一个函数的调用
const scriptStr = `${funcName}(${JSON.stringify(data)})`
// 把拼接的字符串,响应给客户端
res.send(scriptStr)
})
const cors = require('cors')
app.use(cors())
const router = require('./apiRouter')
app.use('/api', router)
app.listen(80, ()=> {
console.log('express 服务器运行在 http://127.0.0.1.80')
})
在网页中使用 jQuery 发起 JSONP 请求
调用 $.ajax() 函数,提供 JSONP 的配置选项,从而发起 JSONP 请求
<!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>
<script src="https://cdn.staticfile.org/jquery/1.10.0/jquery.min.js"></script>
</head>
<body>
<button id="jsonpBut"> JSONP </button>
<script>
$(function(){
// 为 JSONP 按钮绑定点击事件处理函数
$('#jsonpBut').on('click', function(){
$.ajax({
type:'GET',
url:'http://127.0.0.1/api/jsonp',
dataType:'jsonp',
success: function (res) {
console.log(res)
}
})
})
})
</script>
</body>
</html>
log:(点击 JSONP 按钮)