So I’m currently doing a school project where I have a t-sql database, a server (express), and a client side (HTML). I use Cors since my client-side code runs on port “8000” and my server-side code runs on port “8080”. I have tried a lot of different solutions (even chatGPT cant figure this out), but to no avail. Im currently stuck on a “logout” POST request which is being blocked by Cors policy. I have encountered this error several times but somehow something works, dont know how or why. However this time nothing seem to work, I hope some Express/Cors geniuses might see this and give some insight! All answers appreciated:)
My console says. “Access to fetch at ‘http://localhost:8080/api/logout’ from origin ‘http://127.0.0.1:8080’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The value of the ‘Access-Control-Allow-Origin’ header in the response must not be the wildcard ‘*’ when the request’s credentials mode is ‘include’.”
I dont have ‘*’ in my ‘Access-Control-Allow-Origin’ header as you can see here:
Express code:
const cookieParser = require('cookie-parser');
const express = require("express"); // oppsette server
const sql =require('mssql')
const bodyParser = require('body-parser'); // Import the body-parser middleware
const { executeSQL } = require("./Database/db_connect"); // for å koble opp til databasen
const config = require('./Database/config.json');
const cors = require('cors');
const app = express();
const session = require('express-session');
//allow OPTIONS on all resources (I still use cors() in every Endpoint)
app.options('*', cors())
// uses this like this --> app.post('/api/logout', cors(corsOptions), (req, res, next) => {....
const corsOptions = {
origin: 'http://127.0.0.1:8080',
}
// now if i change the "origin" it cant really do anything, and this is supposed to be the correct "origin", but it is read as '*', why? :(
// statisk HTML fil
app.use(express.static('../Klienten'));
// Use the body-parser middleware to parse the request body
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({
secret: 'passord123',
resave: false,
saveUninitialized: true
}));
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:8000');
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
//logout
app.post('/api/logout', cors(corsOptions), async (req, res) => {
try {
// Clear the session cookie and session data
req.session.destroy((error) => {
if (error) {
console.error(`Error logging out user: ${error.message}`);
res.status(500).send('Error logging out user');
} else {
// Return a success response
res.status(200).json({ message: 'User logged out successfully' });
}
});
} catch (error) {
console.error(`Error logging out user: ${error.message}`);
res.status(500).send('Error logging out user');
}
});
now i have several routes/request all from GET/DELETE/POST/PUT etc, a lot of them work, some dont (mostly because I’m not that good yet, and there are other issues). I dot want this question to be super long so i have cut out all of them, except the logout.
My server-side code for the login:
window.addEventListener('DOMContentLoaded', () => {
const logoutButton = document.getElementById('logout');
logoutButton.addEventListener('click', async () => {
try {
await fetch('http://localhost:8080/api/logout', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include' // Include credentials (cookies) in the request
});
// Remove the user_ID from session storage
sessionStorage.removeItem('username');
// Redirect the user to the login page
window.location.href = '/login.html';
} catch (error) {
console.error('Error logging out user:', error);
}
});
});
PS
I have re-written my code several times so it might not be of the best quality nor good structure. Again, all help appreciated!:)