实际不采用,但面试常考。
需要前后端配合,但只支持Get请求。
jsonp概念
浏览器端通过script(支持跨域)标签的src属性,请求服务器上的数据,同时,服务器返回一个函数的调用。这种请求数据的方式叫做JSONP。
Nodejs后端,步骤如下
1、初始化
终端输入npm init 用于生成package.json管理项目中需要的包
2、安装express
使用express框架搭建服务器npm i express@4.17.1
3、新建server.js文件并写入代码
// 1.导入express
const express = require('express')
//2.创建web服务器
const app = express()
//4.监听get请求
app.get('/jsonp-server',(req,res)=>{
const data = {
name:'zhangsan'
}
//将数据转化为字符串
let str = JSON.stringify(data)
//返回函数调用
res.end(`handle(${str})`)
})
//3.启动web服务器
app.listen(80,()=>{
console.log('express server running at http://127.0.0.1')
})
4.在当前目录的终端下执行node server.js开启服务器
浏览器前端
使用文件路径或Live Server运行html文件,在控制台可看到打印出后端返回的数据
<!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 handle(data){
console.log(data);
}
</script>
<script src="http://127.0.0.1:80/jsonp-server"></script>
</body>
</html>