一、什么是跨域问题?

想象一下这样的场景:你开了一家超市(网站A),想从隔壁农贸市场(网站B)进货。但农贸市场的老板说:"不行,我们只供货给认识的商户"。这就是浏览器里的"同源策略"——默认情况下,JavaScript只能访问和当前页面同域名、同端口、同协议的资源。

举个例子:

// 技术栈:JavaScript + Fetch API
// 当前页面URL:https://www.example.com
fetch('https://api.other-site.com/data')  // 不同域名
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('请求失败:', error));

// 控制台会报错:
// Access to fetch at 'https://api.other-site.com/data' from origin 'https://www.example.com' 
// has been blocked by CORS policy

二、常见的跨域解决方案

1. CORS(跨域资源共享)

这是最正规的解决方式,需要后端配合。就像农贸市场老板说:"可以供货,但需要你提供营业执照(HTTP头)"。

// 技术栈:Node.js + Express
const express = require('express');
const app = express();

// 允许特定域名跨域访问
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', 'https://www.example.com');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

app.get('/api/data', (req, res) => {
  res.json({ message: "这是跨域允许的数据" });
});

app.listen(3000, () => console.log('服务器已启动'));

注意事项

  • 生产环境不要用*通配符,应该指定具体域名
  • 复杂请求(如PUT/DELETE)会先发OPTIONS预检请求

2. JSONP(已过时但需要了解)

像通过