AJAX 401错误表示未授权的请求。当客户端尝试访问需要身份验证的资源时,如果没有提供有效的身份验证凭据或提供的凭据无效,服务器将返回401状态码。
$.ajax({
url: 'your-api-endpoint',
type: 'GET',
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + yourToken);
},
success: function(data) {
console.log('Success:', data);
},
error: function(xhr, status, error) {
if (xhr.status === 401) {
// Handle unauthorized access
console.log('Unauthorized, redirecting to login...');
window.location.href = '/login';
} else {
console.error('Error:', error);
}
}
});
确保服务器端正确验证了传入的认证信息。例如,在Node.js中使用Express:
const express = require('express');
const app = express();
app.use((req, res, next) => {
const token = req.headers['authorization'];
if (!token) return res.status(401).send('Access denied.');
try {
const verified = jwt.verify(token, 'your-secret-key');
req.user = verified;
next();
} catch (error) {
res.status(400).send('Invalid token.');
}
});
app.get('/protected', (req, res) => {
res.send('This is a protected route.');
});
app.listen(3000, () => console.log('Server running on port 3000'));
AJAX 401错误通常是由于缺少或无效的认证信息导致的。前端需要在请求中正确设置认证头,后端则需要验证这些信息。通过这种方式,可以有效地处理未授权的请求并提升应用的安全性。
领取专属 10元无门槛券
手把手带您无忧上云