目录
什么是跨域
跨域(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

发起登录请求
javascript
<script setup>
import axios from 'axios'
const authLogin = async () => {
try {
const { data } = await axios.post('http://127.0.0.1:3000/api/v1/users/login', {
"email": "adasdasasda1@qq.com",
"password": "pass1234"
})
} catch (error) {
throw new Error(error)
}
}
</script>
<template>
<main>
<button @click="authLogin">sign</button>
</main>
</template>
浏览器跨域报错

cors中间件解决跨域
流程
1、安装cors依赖
npm i cors
2、引入依赖
javascript
const cors = require('cors');
3、注册中间件
全局注册cors中间件
javascript
app.use(cors());
或为某个路由注册cors中间件
javascript
router.post('/path', cors(), controller);
vue服务进行post请求

请求成功,看到响应头Access-Control-Allow-Origin为*, 为cors的默认设置
配置cors参数
javascript
const corsOptions = {
origin: 'http://192.168.110.61:5173',
//...
};
app.use(cors(corsOptions));
origin: 允许访问资源的特定源

通过查阅github文档查看其他配置
GitHub - expressjs/cors: Node.js CORS middleware
用cors中间件配置同以下
javascript
app.all("*", (req, res, next) => {
//设置允许跨域的域名,*代表允许任意域名跨域
res.header("Access-Control-Allow-Origin", "http://192.168.110.61:5173");
})