React Native中Axios带Basic Auth的GET请求返回401错误(Postman与cURL可正常运行)
React Native中Axios带Basic Auth的GET请求返回401错误(Postman与cURL可正常运行)
我在React Native项目中使用Axios从搭载Tutor LMS插件的WordPress站点API获取数据时遇到了问题:相同的请求在Postman和cURL中都能正常返回结果,但在React Native里却一直返回401 Unauthorized错误,错误响应内容如下:
{
"code": "rest_forbidden",
"message": "Sorry, you are not allowed to do that.",
"data": { "status": 401 }
}
我的Axios请求代码
import axios from 'axios'; export const fetchCourses = async () => { try { const response = await axios.get('https://sub.example.com/wp-json/tutor/v1/courses', { auth: { username: 'key_3f0cc1f7c4fb8bfd2de2455f', password: 'secret_dc5e9ae0fc7e4affe5034b04b8378e0550ca6a5d', }, }); console.log('Courses Data:', response.data); } catch (error) { console.error('Error fetching courses:', error); } };
需要注意的关键信息
- 所用的凭证是完全有效的,在Postman中测试可以正常获取数据。
- 用等效的cURL命令也能得到成功响应:
curl -u key_3f0cc1f7c4fb8bfd2de2455f:secret_dc5e9ae0fc7e4affe5034b04b8378e0550ca6a5d https://sub.example.com/wp-json/tutor/v1/courses
我尝试过的另一种写法(仍失败)
我还手动生成Basic Auth的token并放在请求头里,但还是得到同样的401错误:
export const fetchCourses = async () => { try { const username = 'key_3f0cc1f7c4fb8bfd2de2455f'; const password = 'secret_dc5e9ae0fc7e4affe5034b04b8378e0550ca6a5d'; // 手动Base64编码用户名和密码 //const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64'); const token = btoa(`${username}:${password}`); console.log('Token:', token); const response = await axios.get('https://sub.example.com/wp-json/tutor/v1/courses', { headers: { 'Authorization': `Basic ${token}`, 'Accept': 'application/json', 'Content-Type': 'application/json', 'User-Agent': 'ReactNativeApp/1.0', }, }); console.log('Courses Data:', response.data); } catch (error) { console.error('Error fetching courses:', error.response?.data || error.message); } };
补充细节
- 我在Node.js环境中运行完全相同的代码,能成功获取到数据:

- Node.js和React Native中生成的Auth token是完全一致的。
- 我已经查阅过一个类似的问题,但没能解决我的问题。
环境信息
- React Native: 0.76.3
- Axios: ^1.7.9
请问为什么在React Native中会出现这个401错误?我该如何解决这个问题?
备注:内容来源于stack exchange,提问作者Faisal Shaikh
相关产品推荐
相关产品推荐

