Currently, I am delving into the intricacies of server-client communication as part of my MMORPG project development.
*update: Modifications have been made to the server-side code.
The following snippet showcases the server-side code:
router.post('/login', async (request, response, next) => {
passport.authenticate('login', async (error, user) => {
try {
if (error) {
return next(error);
}
if (!user) {
return next(new Error('Both email and password are required'));
}
request.logIn(user, { session: false }, (err) => {
if (err) {.....
On the other hand, this portion illustrates the client-side code:
function postData(url, data = {}) {
return fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
redirect: 'follow',
body: JSON.stringify(data),
}).then((response) => response.json());
}
login() {
const loginValue = this.loginInput.value;
const passwordValue = this.passwordInput.value;
postData('http://localhost:4000/login', { email: loginValue, password: passwordValue })
.then((response) => {
if (response.status === 200) {
this.startScene('Game');
} else {
console.log(response.message);
window.alert('Invalid username or password');
}
}).catch((error) => {
console.log(error.message);
window.alert('Invalid username or password');
});
}
Upon calling the login() function, the fetch() function throws the following message in the browser console. (The server side is located at http://localhost:4000/login while the client side is at http://localhost:8000.)
Access to fetch at 'http://localhost:4000/login' from origin 'http://localhost:8000'
has been blocked by CORS policy: Response to preflight request doesn't pass access
control check: The value of the 'Access-Control-Allow-Credentials' header in the
response is '' which must be 'true' when the request's credentials mode is 'include'.
LoginScene.js:48 POST http://localhost:4000/login net::ERR_FAILED
Failed to fetch <<-- Displayed error message on browser console
I have made several attempts to rectify this issue without much success.