問題:
上一個博客部署好了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 瀏覽器
也請求到了
到此跨域問題解決。