html代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div>
我要利用jsonp解决跨域问题
</div>
</body>
</html>
<script>
function jsonp({url,params,callback}){
return new Promise((resolve,reject)=>{
let script =document.createElement('script')
window[callback] = function(data){
resolve(data)
document.body.removeChild(script)
}
params = {...params,callback} //wd=b&callback=show
let arrs = []
for(let key in params){
arrs.push(`${key}=${params[key]}`)
}
script.src = `${url}?${arrs.join('&')}`
document.body.appendChild(script)
})
}
jsonp({
url: 'http://localhost:3000/say',
params: { wd: 'Iloveyou' },
callback: 'show'
}).then(data => {
console.log(data)
})
</script>
server.js代码如下:
// server.js
let express = require('express')
let app = express()
app.get('/test', function(req, res) {
let { wd, callback } = req.query
console.log(wd) // 关注小编
console.log(callback) // show
res.end(`${callback}('关注了')`)
})
app.get('/qwer', function(req, res) {
res.end('123')
})
app.listen(3000)