重生之我在学前端——跨域篇
什么是前端跨域?
如果请求的域名、协议或端口有任何不同,浏览器就会认为是跨域请求
- 前端(
http://shicanyyds.com
)尝试向后端服务器(http://api.
)发起请求。shicanyyds
.com - 前端(
http://
)尝试向后端服务器(shicanyyds
.comhttps://
)发起请求。shicanyyds
.com - 前端(
http://
)尝试向后端服务器(
.com:8080shicanyyds
http://
)发起请求。
.com:80shicanyyds
常见解决跨域问题的方法
方法一(node.js中间件CORS)
const express = require('express');
const cors = require('cors');
const app = express();
// 允许所有跨域请求
app.use(cors());
// 只允许特定域名
app.use(cors({
origin: 'http://shicanyyds.com'
}));
app.get('/login', (req, res) => {
res.json({ message: '欢迎登录' });
});
//端口号
app.listen(3000, () => {
console.log('Server running on port 3000');
});
方法二(Nginx反向代理)
server {
listen 80;
server_name api.shicanyyds.com;
location / {
add_header 'Access-Control-Allow-Origin' 'http://shicanyyds.com';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
proxy_pass (填写后端地址);
}
}
方法三(前端代理)
vue在vue.config.js中添加代理配置
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://api.shicanyyds.com',
changeOrigin: true
}
}
}
};
react在package.json中添加代理配置
{
"proxy": "http://api.shicanyyds.com"
}
方法四(JSONP)
JSONP 是一种古老的跨域解决方案,通过 <script>
标签的 src
属性动态加载跨域资源。但它只能用于 GET
请求
方法五(WebSocket)
WebSocket 是一种全双工通信协议,不受同源策略限制。如果后端支持 WebSocket,可以使用它来实现跨域通信
方法六(springboot通过实现 WebMvcConfigurer
接口配置 CORS)
全局配置
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://shicanyyds.com") // 允许的前端域名
.allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的 HTTP 方法
.allowedHeaders("*") // 允许的请求头
.allowCredentials(true); // 是否允许携带凭证
}
}
局部配置
@RestController
@CrossOrigin(origins = "http://shicanyyds.com") // 允许跨域
public class MyController {
@GetMapping("/api/login")
public String Login() {
return "欢迎登录";
}
}
阅读剩余
版权声明:
作者:Shican_FelixLiu
链接:https://www.shicanyyds.cn/index.php/2025/02/17/zhongshengzhiwozaixueqianduankuayupian/
文章版权归作者所有,未经允许请勿转载。
THE END