使用图片跨域方式获取图片数据
server.get(`/mockImg`, (req, res, next) => {
req.headers.origin && res.setHeader(`Access-Control-Allow-Origin`, req.headers.origin)
res.setHeader(`content-type`, `image/gif`)
res.setHeader(`data`, `image/gif`)
var b64string = 'R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs='
var buf = Buffer.from(b64string, 'base64');
res.send(buf)
function getImgBase64(api) {
return new Promise((resove, reject) => {
var img = new Image();
img.setAttribute('crossorigin', 'anonymous')
img.onload = () => {
function getBase64Image(img) {
var canvas = document.createElement('canvas')
var ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0)
return canvas.toDataURL()
}
resove(getBase64Image(img))
}
img.onerror = err => reject(err)
img.src = api
})
}
})
使用 jsonp 方式跨域获取数据
server.get(`/jsonp`, (req, res, next) => {
const {cb} = require('querystring').parse(req.url.replace(/.*\?/, ''))
res.send(`${cb}({a:1})`)
function jsonp(api, cb) {
return new Promise((resove, reject) => {
const cbName = `jsonp${Date.now()}${String(Math.random()).slice(2)}`
window[cbName] = res => {cb && cb(res); resove(res)}
const src = `${api}${api.includes('?') ? '&' : '?'}cb=${cbName}`
const script = document.createElement('script')
script.setAttribute('crossorigin', 'anonymous')
script.src = src
script.onload = () => {
const script = document.querySelector(`script[src*="${cbName}"]`)
script.remove()
delete window[cbName]
}
script.onerror = err => reject(err)
document.body.append(script)
})
}
})