跨域请求是指浏览器在同源策略限制下,禁止网页向协议、域名或端口任意一个不同的服务器发起HTTP请求。CORS全称跨域资源共享,是W3C标准,靠服务器返回特定响应头让浏览器放行跨域访问。JavaScript中处理CORS既要在前端正确发请求,也要服务端配合。

为什么会产生跨域
浏览器同源策略要求请求的协议、域名、端口三者一致。例如下面这些情况都属于跨域:
- 当前页 https://a.com 请求 http://a.com(协议不同)
- 当前页 https://a.com 请求 https://b.com(域名不同)
- 当前页 https://a.com:80 请求 https://a.com:8080(端口不同)
JavaScript前端如何处理CORS
使用fetch发起带CORS的请求
fetch默认以CORS模式发请求,只需服务端返回正确头。前端可显式设置模式与凭据:
// 使用fetch发送跨域请求
fetch('https://api.ipipp.com/data', {
method: 'GET',
mode: 'cors', // 默认值就是cors
credentials: 'include', // 如需携带cookie则设置
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error('跨域请求失败', err));
使用XMLHttpRequest处理
传统方式同样能发跨域请求,浏览器会自动处理预检:
// 使用XMLHttpRequest发送跨域请求
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.ipipp.com/data', true);
xhr.withCredentials = true; // 携带cookie
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
服务端需要返回的头
服务器必须返回以下头浏览器才允许跨域:
| 响应头 | 作用 |
|---|---|
| Access-Control-Allow-Origin | 指定允许访问的域名,如 https://a.com |
| Access-Control-Allow-Credentials | 是否为凭据请求返回 true |
| Access-Control-Allow-Headers | 预检中允许的自定义头 |
预检请求说明
当使用非简单请求方法(如 PUT)或自定义头时,浏览器先发 OPTIONS 预检。服务端需正确响应 OPTIONS:
// Node.js Express 处理预检示例
const express = require('express');
const app = express();
app.options('/data', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', 'https://a.com');
res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.sendStatus(204);
});
常见错误与排查
若控制台报 blocked_by_cors_policy,优先检查服务端是否返回 Access-Control-Allow-Origin。注意文中提到的 <input> 标签是DOM元素,与跨域函数调用 input() 不同。本地调试可用 127.0.0.1 与 192.168.0.1 避开部分限制。
跨域请求CORSJavaScript修改时间:2026-07-27 03:00:09