CORS (Cross-Origin Resource Sharing) 是一种安全机制,它允许网页从不同源的服务器请求资源。当使用 jQuery AJAX 进行跨域请求时,如果服务器返回 401 状态码(未授权),可能会遇到 CORS 相关问题。
在 Firefox 中遇到 401 状态码的 CORS 问题,通常有以下几种原因:
$.ajax({
url: 'https://api.example.com/endpoint',
type: 'GET', // 或 'POST'
crossDomain: true,
xhrFields: {
withCredentials: true // 如果需要发送凭据
},
headers: {
'Authorization': 'Bearer your_token_here' // 如果需要认证
},
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.error('Error:', status, error);
}
});
服务器需要正确配置以下响应头:
Access-Control-Allow-Origin: https://yourdomain.com // 或 * (不推荐)
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true // 如果使用凭据
确保服务器正确处理 OPTIONS 方法:
// Node.js Express 示例
app.options('/api', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', 'https://yourdomain.com');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.sendStatus(200);
});
withCredentials
设置和 Access-Control-Allow-Credentials
头通过以上方法,应该能够解决 Firefox 中 jQuery AJAX 遇到的 CORS 401 问题。
没有搜到相关的文章