python3 tornado api + angular8 + nginx 跨域问题
问题:
上一个博客部署好了api之后,前端开始吊发现了跨域的问题。
接口地址:
http://111.231.201.164/api/houses 服务器上使用的是nginx转发
数据:
前端angular请求
this.http.get(‘http://111.231.201.164/api/houses‘).subscribe((res: any) => { console.log(res); });
目前测试用的Google 和 Firefox两个。
Google 浏览器
需要注意的事我的Google浏览器已经配置过跨域,就是说服务器的代码无论可不可以跨域我的浏览器都可以访问api。
此时还没在后台或者nginx配置跨域。
Firefox 浏览器
而Firefox还是一如既往跨域问题
解决过程:
1、我先是配置的tornado,虽然没有鸟用
这是网上大部分的教程,都是如此说的,但是却没有起作用。
class BaseHandler(tornado.web.RequestHandler): # blog.csdn.net/moshowgame 解决跨域问题 def set_default_headers(self): self.set_header("Access-Control-Allow-Origin", "*") # 这个地方可以写域名 self.set_header("Access-Control-Allow-Headers", "token") self.set_header(‘Access-Control-Allow-Methods‘, ‘POST, GET, OPTIONS‘) self.set_header(‘Access-Control-Allow-Credentials‘, ‘true‘) def write(self, chunk): self.set_header(‘Access-Control-Allow-Origin‘, ‘*‘) super(BaseHandler, self).write(chunk) class MainHandler(BaseHandler): @decoratore def get(self): self.write("Hello, World") # 访问: http://localhost:8888/story/sishen232 # 显示:U get story id is sishen232 class HouseHandler(BaseHandler): ‘‘‘house class‘‘‘ def __init__(self, application, request): ‘‘‘必填参数‘‘‘ super().__init__(application, request) # 预处理 self.data = ByteData(self.request.arguments) self.params = [‘title‘, ‘position‘, ‘size‘, ‘address‘] @decoratore def post(self): ‘‘‘提交House接口‘‘‘ # # 判断提交参数是否有误 # if((‘title‘ not in raw_data) or (‘position‘ not in raw_data)): # self.write(json.dumps( # {"false": {"msg": ‘参数错误‘}}, ensure_ascii=False)) # return code = paramsCheck(self.data, self.params) if code == 1: raw_data = self.data if(‘year‘ not in raw_data): raw_data[‘year‘] = ‘‘ print(raw_data) data = self.application.db.execute( "insert into house(title, position, size, address, year) values(‘{}‘, ‘{}‘, {}, ‘{}‘, ‘{}‘)".format(raw_data[‘title‘], raw_data[‘position‘], float(raw_data[‘size‘]), raw_data[‘address‘], raw_data[‘year‘])) # self.write(json.dumps({"sum": s})) self.write(json.dumps( {"success": {"msg": ‘添加成功‘}}, ensure_ascii=False)) else: self.write(json.dumps( {"false": {"msg": ‘参数错误‘}}, ensure_ascii=False)) def get(self, House_id=‘‘): ‘‘‘ # 获取House接口 # House_id 存在则获取该条数据,不存在获取所有数据 ‘‘‘ sql = ‘select * from house‘ if House_id == ‘‘ else ‘select * from house where id = {id}‘.format( id=House_id) data = self.application.db.query(sql) # self.write(json.dumps({"sum": s})) self.write(json.dumps( {"success": {"msg": ‘获取成功‘, "data": data}}, ensure_ascii=False))
2、nginx配置
方法1没有起作用的话,那多半就是转发出的问题。
location /api/{ allow 111.231.201.164; proxy_pass_header Server; proxy_set_header Host $http_host; proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Scheme $scheme; proxy_pass http://127.0.0.1:8888/; ## 跨域 if ($request_method = ‘OPTIONS‘) { add_header ‘Access-Control-Allow-Origin‘ ‘*‘; add_header ‘Access-Control-Allow-Methods‘ "GET, POST, PUT, DELETE, PATCH, OPTIONS"; add_header ‘Access-Control-Allow-Headers‘ "token"; return 200; } }
修改之后重启nginx。
Google浏览器
还是一样ok
Firefox 浏览器
也请求到了
到此跨域问题解决。
class BaseHandler(tornado.web.RequestHandler):
# blog.csdn.net/m
oshowgame 解决跨域问题
def set_default_headers(self):
self.set_header("Access-Control-Allow-Origin", "*") # 这个地方可以写域名
self.set_header("Access-Control-Allow-Headers", "token")
self.set_header(‘Access-Control-Allow-Methods‘, ‘POST, GET, OPTIONS‘)
self.set_header(‘Access-Control-Allow-Credentials‘, ‘true‘)
def write(self, chunk):
self.set_header(‘Access-Control-Allow-Origin‘, ‘*‘)
super(BaseHandler, self).write(chunk)
class MainHandler(BaseHandler):
@decoratore
def get(self):
self.write("Hello, World")
# 访问: http://localhost:8888/story/sishen232
# 显示:U get story id is sishen232
class HouseHandler(BaseHandler):
‘‘‘house class‘‘‘
def __init__(self, application, request):
‘‘‘必填参数‘‘‘
super().__init__(application, request)
# 预处理
self.data = ByteData(self.request.arguments)
self.params = [‘title‘, ‘position‘, ‘size‘, ‘address‘]
@decoratore
def post(self):
‘‘‘提交House接口‘‘‘
# # 判断提交参数是否有误
# if((‘title‘ not in raw_data) or (‘position‘ not in raw_data)):
# self.write(json.dumps(
# {"false": {"msg": ‘参数错误‘}}, ensure_ascii=False))
# return
code = paramsCheck(self.data, self.params)
if code == 1:
raw_data = self.data
if(‘year‘ not in raw_data):
raw_data[‘year‘] = ‘‘
print(raw_data)
data = self.application.db.execute(
"insert into house(title, position, size, address, year) values(‘{}‘, ‘{}‘, {}, ‘{}‘, ‘{}‘)".format(raw_data[‘title‘], raw_data[‘position‘], float(raw_data[‘size‘]), raw_data[‘address‘], raw_data[‘year‘]))
# self.write(json.dumps({"sum": s}))
self.write(json.dumps(
{"success": {"msg": ‘添加成功‘}}, ensure_ascii=False))
else:
self.write(json.dumps(
{"false": {"msg": ‘参数错误‘}}, ensure_ascii=False))
def get(self, House_id=‘‘):
‘‘‘
# 获取House接口
# House_id 存在则获取该条数据,不存在获取所有数据
‘‘‘
sql = ‘select * from house‘ if House_id == ‘‘ else ‘select * from house where id = {id}‘.format(
id=House_id)
data = self.application.db.query(sql)
# self.write(json.dumps({"sum": s}))
self.write(json.dumps(
{"success": {"msg": ‘获取成功‘, "data": data}}, ensure_ascii=False))
相关推荐
chuckchen 2020-10-31
Will0 2020-10-12
Dreamhome 2020-10-09
xirongxudlut 2020-09-28
星辰大海的路上 2020-09-13
chaochao 2020-08-31
猪猪侠喜欢躲猫猫 2020-08-17
快递小可 2020-08-16
shengge0 2020-07-26
巩庆奎 2020-07-21
张文倩数据库学生 2020-07-19
xirongxudlut 2020-07-18
Ericbig 2020-07-18
kyelu 2020-07-09
liangzhouqu 2020-07-07
GuoSir 2020-06-28
chaigang 2020-06-27
pythonxuexi 2020-06-25