// url为请求的网址,data为url携带的参数
let jsonp = function (url, data = {}, callback) {
// 转化data为url字符串形式,例{a: 1, b: c} => a=1&b=c&
// indexOf未检查到?则返回-1
let str = url.indexOf('?') === -1 ? '?' : '&'
if (data !== {}) {
for (let key in data) {
str += `${key}=${data[key]}&` // es6的模板字符串
}
}
// callback参数,指定回调函数的名字
let n = 'jsonp_' + Math.random().toString().replace('.', '').substr(1, 6)
str += 'callback=' + n
// 创建script标签并添加src属性
let s = document.createElement('script')
s.src = url + str // 将参数添加到url上
// 回调挂载在全局对象上
window[n] = function (data) {
callback(data)
document.body.removeChild(s) // 用完script标签就删除
}
document.body.appendChild(s)
}
// 测试效果
jsonp('http://localhost:3000/user?username=zs&age=20', { email: "123" }, function (data) { console.log(data) })
server
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
// app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
// post请求体中的Content-Type为:application/json,则配置如下:
// 解决跨域的问题
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Headers', 'Content-Type');
// res.header("Access-Control-Allow-Headers", "X-Requested-With");
// res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
// res.header("X-Powered-By",' 3.2.1')
// res.header("Content-type", "application/json");
next();
});
app.get('/user', function (req, res) {
let { callback } = req.query
if (callback) {
res.setHeader('Content-type', 'application/javascript');
res.send(callback + '({ message: "Get请求成功", code: 1 })')
} else {
res.send({ message: "Get请求成功", code: 1 })
}
})
app.post('/user', (req, res) => {
res.send({ message: "Post请求成功", code: 1 })
})
app.listen(3000, () => {
console.log('服务器启动成功');
})