So, I am trying to use Create React App with Express.js on the back-end. I am running the two on different ports — Front-end is on 3000, back-end is on 3001. I am using Local Passport Strategy for the login system. And the login system works fine. On the front-end, I have a register/login form which sends a post request to localhost:3001/register(or login) and it successfully registers/logs the user in. Then, I have another route on the back-end which is supposed to return the data of the user who is currently logged in, if there is a logged in user, or otherwise, return an object with a "Not authenticated" message.
app.get('/loggedUserInfo', function(req, res) {
if (req.user) {
console.log(req.user);
res.json(req.user);
} else {
console.log('not authenticated');
res.json({'message': 'not authenticated'});
}
});
Now, on the client side, I want to modify the navigation bar in accordance to the response of this request. For example, if a user is logged in, I want to have a navbar that contains a logout button, and if a user is not logged in, I want to have a navbar with a login and a register button. So, in the React component, I have this relevant code:
componentDidMount() {
fetch('localhost:3001/loggedUserInfo')
.then(res => console.log(res.json()));
}
This is supposed to change the state of the component, but it logs the response to the console, just for testing. And every single time, even when the user IS logged in, it returns the "not authenticated" object. It's like the user is never logged in.
BUT, on the other hand, if I go to localhost:3001/loggedUserInfo in my browser, after the user has logged in, I DO get the expected result. It returns the user info that I need.
This has really been bugging me, I can't seem to figure out why this happens. I need the data on the client side.
In case anyone wants to see my app.js file, here is the relevant code (in order), where I think I include everything that needs to be there:
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bodyParser = require('body-parser');
var cors = require('cors');
app.use(cors());
app.use(session({
secret: 'secretKey',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));