洛阳网站建设设计公司,公司建一个网站多少费用,潍坊网站建设联系电话,企业推广平台排行榜目录
什么是跨域
示例
postman请求
前端请求
cors中间件解决跨域
流程
配置cors参数 什么是跨域
跨域#xff08;Cross-Origin#xff09;是指在 Web 开发中#xff0c;当一个网页的源#xff08;Origin#xff09;与另一个网页的源不同时#xff0c;就发生了跨域…目录
什么是跨域
示例
postman请求
前端请求
cors中间件解决跨域
流程
配置cors参数 什么是跨域
跨域Cross-Origin是指在 Web 开发中当一个网页的源Origin与另一个网页的源不同时就发生了跨域。同源策略Same-Origin Policy是浏览器的一项安全策略限制了一个源下的文档或脚本如何能与另一个源下的资源进行交互。
同源是指两个 URL 具有相同的协议http/https、主机domain和端口port。如果这两个URL的这三个部分中任何一个不同就被认为是不同源即跨域。
示例
开启一个node服务服务地址为http://127.0.0.1:3000
postman请求
postman对服务发起post登录请求 请求成功。postman不受跨域影响原因主要是因为postman是一个独立的桌面应用程序而不是运行在浏览器中的 Web 应用。
前端请求
开启一个前端项目服务比如vue 发起登录请求
script setupimport axios from axiosconst authLogin async () {try {const { data } await axios.post(http://127.0.0.1:3000/api/v1/users/login, {email: adasdasasda1qq.com,password: pass1234})} catch (error) {throw new Error(error)}}
/scripttemplatemainbutton clickauthLoginsign/button/main
/template浏览器跨域报错 cors中间件解决跨域
流程
1、安装cors依赖
npm i cors
2、引入依赖
const cors require(cors);
3、注册中间件
全局注册cors中间件
app.use(cors()); 或为某个路由注册cors中间件
router.post(/path, cors(), controller);
vue服务进行post请求 请求成功看到响应头Access-Control-Allow-Origin为* 为cors的默认设置
配置cors参数
const corsOptions {origin: http://192.168.110.61:5173,//...
};app.use(cors(corsOptions));
origin 允许访问资源的特定源 通过查阅github文档查看其他配置
GitHub - expressjs/cors: Node.js CORS middleware
用cors中间件配置同以下
app.all(*, (req, res, next) {//设置允许跨域的域名*代表允许任意域名跨域res.header(Access-Control-Allow-Origin, http://192.168.110.61:5173);
})