|
- 代码实现(代理服务器,返回响应体和进行跨域处理后的headers)
- import aiohttp
- from functools import wraps
- from aiohttp import web
- corscode = {
- 'Access-Control-Allow-Origin': '*',
- 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', # 需要限制请求就在这里增删
- 'Access-Control-Allow-Headers': '*',
- 'Server':'is my server',
- }
- # 实例化路由
- routes = web.RouteTableDef()
- # 异步json序列化
- def jsondump(func):
- @wraps(func)
- async def wrapper(*args,**kwargs):
- result = await func(*args,**kwargs)
- try:
- return json.dumps(result ,ensure_ascii=False)
- except:
- return result
- return wrapper
- # 封装一下web.json_resp
- # def wj(dt):
- # return web.json_response(dt)
- wj = lambda dt: web.json_response(dt)
- # 处理OPTIONS和跨域的中间件
- @jsondump
- async def options_middleware(app, handler):
- async def middleware(request):
- # 处理 OPTIONS 请求,直接返回空数据和允许跨域的 header
- if request.method == 'OPTIONS':
- return web.Response(headers=corscode)
- # 继续处理其他请求
- response = await handler(request)
- # 为每次响应添加header
- try:
- response.headers.update(corscode)
- except Exception as e:
- return response
- return response
- return middleware
- @jsondump
- @routes.view(r'/get')
- async def geturl(request):
- url = request.query.get('url')
- if not url:
- return wj({"data":"参数错误"})
- async with aiohttp.ClientSession() as session:
- async with session.get(url) as response:
- # 检查请求是否成功,如果不成功,可以根据需要进行处理
- if response.status == 200:
- file = await response.read()
- return web.Response(body=file, headers=response.headers)
- if __name__ == '__main__':
- app = web.Application()
- app.add_routes(routes)
- app.middlewares.append(options_middleware)
- web.run_app(app)
复制代码- function downloadfile(url, fileName) {
- var xhr = new XMLHttpRequest();
- xhr.open('GET', url, true);
- xhr.responseType = 'blob';
- xhr.onload = function() {
- if (xhr.status === 200) {
- var blob = xhr.response;
- var a = document.createElement('a');
- var url = window.URL.createObjectURL(blob);
- a.href = url;
- a.download = fileName;
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- window.URL.revokeObjectURL(url);
- }
- };
- xhr.send();
- }
复制代码- downloadfile(url, fileName)
复制代码
- 结果
可以正常下载
并且在响应头中能看到Server:is my server
同时可以看到添加成功的Allow-Origin响应头
来源:https://www.cnblogs.com/ymer/p/17560121.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作! |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?立即注册
x
|