unexpected status 401 Unauthorized: 无效的令牌 (request id: 20260903133954461990053c1...
错误信息
AI 解决方案
🔍 报错分析
1. 🌐 错误翻译
原文:unexpected status 401 Unauthorized: 无效的令牌 (request id: 20260903133954461990053c14228f5FLoX381E), url: https://www.dmxapi.cn/v1/responses
译文:意外的401状态码 未授权:无效的令牌 (请求ID:20260903133954461990053c14228f5FLoX381E),URL:https://www.dmxapi.cn/v1/responses
2. 🎯 原因分析
该错误的根本原因是API请求使用了无效的身份验证令牌,导致服务器拒绝授权。具体表现为:
/v1/responses时3. 💡 解决方案
检查并修复令牌相关问题,以下是常见修复方式:
#### 场景1:令牌未传递或传递错误
// 修复后的代码 - 确保正确设置Authorization头
const fetch = require('node-fetch');
const options = {
method: 'GET',
headers: {
'Authorization': 'Bearer YOUR_VALID_API_TOKEN_HERE', // 替换为有效令牌
'Content-Type': 'application/json'
}
};
fetch('https://www.dmxapi.cn/v1/responses', options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
#### 场景2:令牌过期需重新获取
``javascript
// 修复后的代码 - 先获取新令牌再请求接口
const axios = require('axios');
// 1. 获取新的访问令牌
const getNewToken = async () => {
try {
const response = await axios.post('https://www.dmxapi.cn/v1/token', {
client_id: 'YOUR_CLIENT_ID',
client_secret: 'YOUR_CLIENT_SECRET'
});
return response.data.access_token;
} catch (error) {
throw new Error('获取令牌失败: ' + error.message);
}
};
// 2. 使用新令牌请求目标接口
const fetchResponses = async () => {
try {
const token = await getNewToken();
const response = await axios.get('https://www.dmxapi.cn/v1/responses', {
headers: {
'Authorization': Bearer ${token}`
}
});
return response.data;
} catch (error) {
throw new Error('请求失败: ' + error.message);
}
};
// 执行