解决javascript调用本地sanic接口报跨域错误的问题

在py代码中利用middleware()方法修饰request/response即可,无需别的操作。 

from sanic import Sanic, HTTPResponse, Request

app=Sanic('Sanic_Server') @app.middleware("request") def cors_middle_req(request: Request): """路由需要启用OPTIONS方法""" if request.method.lower() == 'options': allow_headers = [ 'Authorization', 'content-type' ] headers = { 'Access-Control-Allow-Methods': ','.join(['GET','POST','OPTIONS']), 'Access-Control-Max-Age': '86400', 'Access-Control-Allow-Headers': ', '.join(allow_headers), } return HTTPResponse('', headers=headers) @app.middleware("response") def cors_middle_res(request: Request, response: HTTPResponse): """跨域处理""" allow_origin = '*' response.headers.update( { 'Access-Control-Allow-Origin': allow_origin, } )

 

posted @ 2023-04-11 13:04  morein2008  阅读(73)  评论(0编辑  收藏  举报