jsonp通过动态请求脚本文件,可以非常方便的实现不同域名下的数据请求,不过该方法只能发送get请求。
示例:
<!DOCTYPE html>
<html>
<head>
<title>jsonp</title>
<meta charset="utf-8">
</head>
<body>
<button onclick="doJsonp('testFn');">发送JSONP请求</button>
<script type="text/javascript">
function doJsonp(callbackName) {
var script = document.createElement('script');
script.src = '/api?callbackName='+callbackName
document.getElementsByTagName('head')[0].appendChild(script);
window[callbackName] = function(data) {
console.log(data);
script.parentNode.removeChild(script);
}
}
</script>
</body>
</html>
server.js
const express = require('express');
const fs = require('fs');
const mime = require('mime');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
app.use(bodyParser.json());//数据JSON类型
app.use(bodyParser.urlencoded({ extended: false }));//解析post请求数据
app.get('/api',function(req,res){
res.send(`${req.query.callbackName}('服务器数据')`);
})
app.get('/*', function(req,res){
sendFile(req, res);
});
app.listen(8080);
console.log('listen 8080')
function sendFile(req,res){
var realPath = __dirname+req.url;
var exist = fs.existsSync(realPath);
if(exist){
var file = fs.readFileSync(realPath);
res.writeHead(200, {
'Content-Type': mime.getType(path.basename(realPath)),
});
res.end(file);
console.log('send static file:'+realPath);
} else {
res.writeHead(404);
}
}