Issue
I am using Expo Client for development and I am not able to send a login API call.
onSubmit fuction
const onSubmit = async (username, password)=>{
console.log(username);
console.log(password);
await axios.post(
'https://backend.unknownchats.com/accounts/login/',
{
username: username,
password: password,
},
{
headers: {
'Content-Type': "application/json",
'Accept': "application/json",
}
}
).then(res=>{
console.log(res.data);
if (res.data.status==="success"){
localStorage.setItem('username',res.data.username);
localStorage.setItem('token',res.data.token);
navigation.navigate('Settings');
}else{
setError(res.data.error);
}
}).catch(err=>console.log(err));
}
Take a look at the attached error code.
sumit 97127516
Network Error
at node_modules\axios\lib\core\createError.js:17:22 in createError
at node_modules\axios\lib\adapters\xhr.js:120:6 in handleError
at node_modules\event-target-shim\dist\event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent
at node_modules\react-native\Libraries\Network\XMLHttpRequest.js:609:10 in setReadyState
at node_modules\react-native\Libraries\Network\XMLHttpRequest.js:396:6 in __didCompleteResponse
at node_modules\react-native\Libraries\vendor\emitter\_EventEmitter.js:135:10 in EventEmitter#emit
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:414:4 in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:113:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:365:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112:4 in callFunctionReturnFlushedQueue
Solution
I've tested your code, there is no syntax error. But I noticed that the server doesn't respond to the request. When tested with anther baseUrl, it works great. But with https://backend.unknownchats.com/accounts/login/
I got the same error as you, Network error, in insomnia and postman, I got a SSL error. So the problem is not your code, but the server.
My advice is to test your api requests on Insomnia or Postman, before using it.
So.. the first thing is that you're using the "await" and "then" async method in the same async function.
The best method is using "await".. surrounded by try catch.
Another tip is that, when the object key is the same as the prop passed in value, you can use only the prop name, I'll set above.
The second point is that, axios has its own error data handler. The error you sent, is the default one.
So, to see the error data, you can console.log(error.response.data)
in catch.
try{
const {data} = await axios.post(
'https://backend.unknownchats.com/accounts/login/',
{
username,
password,
},
{
headers: {
'Content-Type': "application/json",
'Accept': "application/json",
}
}
);
console.log(data);
}catch(e){
console.log(e.response.data);
}
Let me know if you could find the response error.
Cheers! :D
Answered By - Jhony Spark
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.