hasbeenblockedbythecurrent(解决has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’报错跨域问题)
关于前后端分离踩过的坑
故事起因:前天晚上 ,在计划中学完了一个前端获取后端请求的框架叫axios 。然后准备用axios 、vue 、以及fastapi(一个Python的web框架)写一个前后端分离的小demo 。结果变成了事故 ,竟然报错了。
主要错误是:has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ 。大概的意思是 ,已被CORS策略阻止:无“访问控制允许来源 ” 。当时我也百度了一下CORS后来因为自己懒了 ,所以就去问一个朋友 ,然后他就让我去搜索如果解决跨域问题 。(这个朋友还说了一下一般如何百度 ,技术栈+问题) ,所以明确一下解决跨域问题 ,技术栈在后端 。接下来就是处理该问题的过程!!!
一、什么是源和跨域?源(origin)就是协议 、域名和端口号 。
URL由协议 、域名 、端口和路径组成 ,如果两个URL的协议 、域名和端口全部相同,则表示他们同源 。否则 ,只要协议 、域名 、端口有任何一个不同 ,就是跨域 。举个例子:http://127.0.0.1:5500/VueStudy/test.html是一个前端的URL
后端接口 是否跨域 原因 http://127.0.0.1:8081/test 是 端口号不一样 http://127.0.0.1:5500/test (如果前端端口和后端端口在同一台机器上,会有端口占用的问题) 否 https://127.0.0.1:8081/test 是 协议不一样 二 、什么是同源策略?(参考百度百科)当一个浏览器的两个tab页中分别打开来 百度和谷歌的页面
当浏览器的百度tab页执行一个脚本的时候会检查这个脚本是属于哪个页面的 ,
即检查是否同源 ,只有和百度同源的脚本才会被执行 。
如果非同源,那么在请求数据时 ,浏览器会在控制台中报一个异常 ,提示拒绝访问 。
所以刚刚前端的请求不满足同源策略 ,所以被浏览器检测出来了 ,然后报了一个异常。
三 、fastapi 跨域解决方案解决思路就是在后台把前端的 ”源“加进去即可 ,其他技术的思路也都差不多 。
前端代码(test.html)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script> <title>Document</title> </head> <body> <div id="app"> <input type="button" value="获取后端数据" @click="login"> <h5>{{message}}</h5> </div> <script> var app = new Vue({ el: "#app", data: { message: "你好前后端分离" }, methods: { login: function() { var that = this axios.get("http://127.0.0.1:8081/test") .then(function(response) { console.log(response) that.message = response.data }) } } }) </script> </body> </html>后端代码(没有解决跨域app.py)
import uvicorn from fastapi import FastAPI, Body app = FastAPI() # 模拟服务端test接口 @app.get("/test") def get_login(): return "this is fastapiApp" if __name__ == __main__: # 服务端端口是 8080! uvicorn.run(app="app:app", reload=True, host="127.0.0.1", port=8081)后端代码(解决跨域问题app.py)
import uvicorn from fastapi import FastAPI, Body # 1 、导入对应的包 from fastapi.middleware.cors import CORSMiddleware app = FastAPI() # 2、声明一个 源 列表;重点:要包含跨域的客户端 源 origins = ["*"] # 3 、配置 CORSMiddleware app.add_middleware( CORSMiddleware, allow_origins=origins, # 允许访问的源 allow_credentials=True, # 支持 cookie allow_methods=["*"], # 允许使用的请求方法 allow_headers=["*"] # 允许携带的 Headers ) # 模拟服务端test接口 @app.get("/test") def get_login(): return "this is fastapiApp" if __name__ == __main__: # 服务端端口是 8080! uvicorn.run(app="app:app", reload=True, host="127.0.0.1", port=8081)总的来说 ,这个问题看似很难 ,其实只要你知道 ,技术栈+问题 ,明白方向就不是很难了 。
创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!