使用图片跨域方式获取图片数据 使用 jsonp 方式跨域获取数据
使用图片跨域方式获取图片数据
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 }) } // getImgBase64(`http://localhost:9001/api/t/mockImg`) })
使用 jsonp 方式跨域获取数据
server.get(`/jsonp`, (req, res, next) => { // 使用 jsonp 方式跨域获取数据 const {cb} = require(‘querystring‘).parse(req.url.replace(/.*\?/, ‘‘)) res.send(`${cb}({a:1})`) function jsonp(api, cb) { // 从 jsonp 中获取数据 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) }) } // jsonp(`http://localhost:9001/api/t/jsonp`) })
?
相关推荐
zmosquito 2020-05-10
somebodyoneday 2020-04-22
fengchao000 2020-04-22
fengchao000 2020-04-11
fengchao000 2020-03-05
fengchao000 2020-06-17
adonislu 2020-05-16
adonislu 2020-05-10
Richardxx 2020-03-07
somebodyoneday 2020-03-06
somebodyoneday 2020-02-16
baijinswpu 2020-01-29
fengchao000 2020-01-10
fengchao000 2019-12-25
newthon 2019-12-23
somebodyoneday 2013-07-11
qianqianxiao 2015-08-13