CORS (Cross-Origin Resource Sharing) 是一种安全机制,它允许网页从不同域(origin)的服务器请求资源。浏览器出于安全考虑,默认禁止跨域请求,除非服务器明确允许。
确保服务器返回正确的 CORS 头:
Access-Control-Allow-Origin: * # 或指定具体域名
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With
Access-Control-Allow-Credentials: true # 如果需要发送凭证
$.ajax({
url: 'https://api.example.com/data',
type: 'GET',
dataType: 'json',
crossDomain: true,
xhrFields: {
withCredentials: true // 如果需要发送cookie等凭证
},
headers: {
'Authorization': 'Bearer token123' // 自定义头
},
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
对于非简单请求(如带自定义头或非GET/POST/HEAD方法),浏览器会先发送OPTIONS预检请求:
// 服务器需要正确处理OPTIONS请求
if (request.method === 'OPTIONS') {
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
response.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
response.statusCode = 204;
response.end();
return;
}
仅限开发环境使用,生产环境应正确配置CORS:
--disable-web-security
参数)Access-Control-Allow-Origin
头Access-Control-Allow-Credentials: true
且Access-Control-Allow-Origin
不能为*
Access-Control-Allow-Origin: *
与withCredentials: true
同时使用通过以上方法,可以解决大多数jQuery Ajax遇到的CORS问题。
没有搜到相关的沙龙