我需要帮助解决这个问题。我是react native和javascript的新手。现在我正在尝试将react native应用程序与API连接起来。这个过程要求我首先通过axios.post
获取令牌,然后才能使用axios.get
获取数据。
简而言之,以下是我的代码片段。
... // code
const TOKEN_URL = 'https://test.co/testing/tokens'
const DATA_URL = 'https://test.co/testing/data/page1'
const getToken = () => {
axios.post(TOKEN_URL, {
email: 'email',
password: 'password',
role: 'user'
})
.then((response) => {
//console.log(response.data.token);
return response.data.token;
})
.catch((error) => {
console.log(error);
});
};
//'export' here is for use in other code: example onPress function
export const fetchDriver = () => {
const config = {
headers: {
'Bearer': getToken()
}
};
axios.get(DRIVER_URL, config)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
};
我期望的控制台日志应该是这样的:
{
"timestamp": 1510038433,
"verb": "GET",
"object": "student",
"data": {
"age": "12",
"id": "90000",
"name": "Test Student",
"emergencyName": "asd",
"createdAt": "2017-10-04T05:39:39+00:00"
}
}
但是我一直收到错误提示,显示请求失败,状态码为400
我正在使用Expo开发这个应用程序。
关于错误的详细信息如下:
- node_modules/axios/lib/core/createError.js:16:24 in createError
- node_modules/axios/lib/core/settle.js:19:6 in settle
- node_modules/axios/lib/adapters/xhr.js:78:13 in handleLoad
- node_modules/event-target-shim/lib/event-target.js:172:43 in dispatchEvent
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:540:23 in
setReadyState
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:381:25 in
__didCompleteResponse
- node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:182:12 in
emit
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:306:47 in
__callFunction
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:108:26 in
<unknown>
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:269:6 in
__guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:107:17 in
callFunctionReturnFlushedQueue
如果错误来自api/server,我没有任何编辑权限。
如果代码片段中有任何遗漏的地方,请帮助我。感谢您的帮助和建议。
console.log(response.data.token)
进行了检查,它正确地返回了令牌。我甚至尝试直接硬编码令牌,但结果仍然相同。 - Ling