项目目录
后端代码
首先安装依赖:npm i express cors
/server.js
const express = require('express');
const cors = require('cors');
const https = require('https');
const app = express();
//解决跨域
// app.use(cors());
//获取post请求的参数
app.use(express.json());
//jsonp 请求
app.get('/jsonp', (req, res) => {
console.log(req.url);
console.log(req.query);
getText((data) => {
res.send(req.query.callback + '(' + JSON.stringify({
code: '0',
msg: data
}) + ')')
});
})
//post 请求
app.post('/getData', (req, res) => {
console.log(req.url);
console.log(req.body);
getText((data) => {
res.send({
code: '0',
msg: data
});
});
})
function getText(fn) {
//发送请求
https.get('https://api.uixsj.cn/hitokoto/get?type=social', (data) => {
var body = [];
data.on('data', (chunk) => {
body.push(chunk);
});
data.on('end', () => {
body = Buffer.concat(body);
fn(body.toString())
});
});
}
app.listen('7777', () => {
console.log('后端启动在7777端口');
})
前端代码
/index.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>jsonp</title>
<style>
body,
button {
font-size: 30px;
text-align: center;
}
button {
cursor: pointer;
}
div {
margin-top: 20px;
}
</style>
</head>
<body>
<button onclick="getJsonpData()">jsonp获取</button>
<button onclick="getData()">post获取</button>
<div id="div" style="color: pink;"></div>
<script>
const div = document.getElementById('div');
const ip = 'http://localhost:7777';
function show(data) {
if (data.code === '0') {
div.innerText = data.msg;
}
}
function getJsonpData() {
const body = document.querySelector('body');
const script = document.createElement('script');
script.src = ip + '/jsonp?name=摸鱼&callback=show';
body.appendChild(script);
}
function getData() {
fetch(ip + '/getData', {
method: 'post',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
a: 1
})
}).then(res => res.json()).then(res => {
show(res);
})
}
</script>
</body>
</html>
项目运行及页面展示
1、利用live-server
等插件以服务器方式启动前端页面
2、使用 node server.js
启动后端代码
如果后端代码注释了解决跨域 app.use(cors());
这句话,那么只有jsonp请求正常,post请求会报跨域错误:
如果解开 app.use(cors());
,则两种方式都可以正常请求