i’m try to connect to my project but i can only connect using localhost adress if try to connect with other device in the same wifi network with the below listed ip cors block them. What im doing wrong in my code?
this how i setup cors in my js file server
const allowedOrigins = ['http://localhost:3000', 'http://192.168.50.52', 'http://192.168.50.121'];
const corsOptions = {
origin: function (origin, callback) {
// Allow requests with no origin (like mobile apps or curl requests)
if (!origin) return callback(null, true);
if (allowedOrigins.indexOf(origin) !== -1) {
callback(null, true); // Origin is allowed
} else {
callback(new Error('CORS not allowed for this origin')); // Origin is not allowed
}
},
credentials: true,
optionsSuccessStatus: 200
};
app.use(cors(corsOptions));
app.options('*', cors(corsOptions)); // Enable pre-flight across-the-board
When i use the browser in my localhost device and i type http://localhost:3000 all work correct i get direct to the login page i insert password and staff_number and the login is successful
// MARK: Routes server
app.get('/', (req, res) => {
console.log("SERVER response to get /");
if (req.session.isAuthenticated) {
res.status(200).json({
message: "Welcome to the homepage!",
userInfo: req.session.userInfo // Ensure userInfo is passed correctly
});
} else {
console.log('Unauthorized reuqest to /');
res.status(401).json({ error: "Unauthorized" });
}
});
//MARK: Login
app.post('/login', (req, res) => {
console.log("SERVER response to post Login");
const { staffNumber, password } = req.body;
console.log('staffnumber:', staffNumber, 'password:', password);
// query to the database to check if the user exist field staff_number and password
db.query('SELECT * FROM amu_users WHERE staff_number = $1 AND password = $2', [staffNumber, password], (err, result) => {
if (err) {
console.error('Error executing query', err);
res.status(500).send('Internal server error');
} else {
if (result.rows.length === 1) {
// the user is authenticated
req.session.userInfo = result.rows[0];
req.session.isAuthenticated = true;
res.status(200)
res.json({result:'success', userInfo: req.session.userInfo});
} else {
res.status(401).send('Unauthorized');
}
}
});
});
But if i try my iphone and my ipad to point at the localhost ip http://192.168.50.6:3000 i get present the login page but cors reject my connection.
I dont know what i can check more, as you can see from my code above i allowed the connection from both ipad and iphone local ip.
thanks