1.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>
<script src="https://cdn.staticfile.org/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<button id="btnget">GET</button>
<button id="btnpost">POST</button>
<button id="btndelete">DELETE</button>
<button id="btnjsonp">JSONP</button>
<script>
$(function() {
// 1.测试GET接口
$('#btnget').on('click', function() {
// 发起ajax请求
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:81/get',
data: {
name: 'sy',
age: 18
},
success: function(res) {
console.log(res);
}
})
})
// 2.测试POST接口
$('#btnpost').on('click', function() {
// 发起ajax请求
$.ajax({
type: 'POST',
url: 'http://127.0.0.1:81/post',
data: {
name: 'oliver',
age: 22
},
success: function(res) {
console.log(res);
}
})
})
$('#btndelete').on('click', function() {
// 发起ajax请求
$.ajax({
type: 'DELETE',
url: 'http://127.0.0.1:81/delete',
data: {
name: 'delete',
age: 100
},
success: function(res) {
console.log(res);
}
})
})
$('#btnjsonp').on('click', function() {
// 发起ajax请求
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:81/jsonp',
dataType: 'jsonp',
success: function(res) {
console.log(res);
}
})
})
})
</script>
</body>
</html>
sy.js コード:
// 1.导入express包
const express = require('express');
const { process_params } = require('express/lib/router');
// 创建一个web服务器
const app = express();
app.use(express.urlencoded({ extends: false }));
// 必须在配置cors中间件之前配置jsonp接口 jsonp只支持get请求
app.get('/jsonp', (req, res) => {
// 定义jsonp接口具体的实现过程
// 1.得到函数的名称
const funcname = req.query.callback;
console.log(funcname);
// 2.定义要发送到客户端的数据对象
const data = { name: 'sy', age: 18 };
// 3.拼接出一个函数的调用
const dostr = `${funcname}(${JSON.stringify(data)})`;
// 4.把拼接的字符串响应给客户端
res.send(dostr);
})
// 导入cors模块
const cors = require('cors');
app.use(cors());
// 导入路由
const router = require('./router');
// 注册路由
app.use(router);
app.listen(81, () => {
console.log('running!');
})
router.js コード:
// 1.导入express包
const express = require('express');
// 2.创建路由
const router = express.Router();
// 3.挂载具体路由
router.get('/get', (req, res) => {
res.send({
status: 100,
msg: 'getmsg',
data: req.body
})
})
router.post('/post', (req, res) => {
res.send({
status: 101,
msg: 'postmsg',
data: req.body
})
})
router.delete('/delete', (req, res) => {
res.send({
status: 666,
msg: 'deletemsg',
data: req.body
})
})
// 4.向外导出路由对象
module.exports = router;
「JSONP」ボタンをクリックして結果を出力します。