I am trying to make requests to my local backend from my react-native app however, whenever I call a new request the session id changes which causes it to fail. I first make a POST request to login which succeeds and returns an object containing my login information. I then try to make a GET request to access the devices page, however my authChecker() function does not recognize the sessionID and sends a 401 error message:
'You have been signed out, please return to the login page'.
I looked into the network tab in my app web page and the values of the session id for my login and devices pages are different (it should be the same).
I already have a functioning local backend and web site however I am trying to create a react app that also uses the backend to display the information on mobile phones. I am using Expo to create my react app and currently I am testing it on the web on http://10.0.10.162:19006.
This is the code in my app that makes requests to the local backend.
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function GetDevices() {
const [expiredDevices, setExpiredDevices] = useState([]);
useEffect(() => {
axios.post('http://localhost:8080/api/login', {
email: '',
password: '',
visitorId: '',
})
.then((response) => {
console.log('The authorization token is: ', response.data.user);
axios.get('http://localhost:8080/api/devices', {
headers: {
Authorization: `Bearer ${response.data.user}`,
},
})
.then((response) => {
console.log('Data from axios: ', response.data);
setExpiredDevices(response.data);
})
.catch((error) => {
console.log(error.response);
});
})
.catch((error) => {
console.log(error.response);
});
}, []);
return (
expiredDevices
);
}
export default GetDevices;
In my app.js for my backend, I have this line which authenticates the user.
app.use('/api/devices', authChecker(true), devicesRouter);
The authChecker() code:
/**
* @fileoverview middlewares and helpers
*/
// Ensure the user is authenticated, either redirect them to login or return 401 for the frontend
module.exports.authChecker = (backend) => {
return (req, res, next) => {
if (!req.session.user) {
if (backend) {
res.status(401).send('You have been signed out, please return to the login page');
} else {
res.redirect(`/login?redirect=${encodeURIComponent(req.originalUrl)}`);
}
} else {
next();
}
};
};
And this is the session value in the network tab:
