0

I am learning server-client communication in the course of making MMORPG project.

*update: server side code is edited.

This is 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('email and password are required'));
      }
      request.logIn(user, { session: false }, (err) => {
        if (err) {.....
  

This is 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.loginInpout.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('invald username or password');
        }
      }).catch((error) => {
        console.log(error.message);
        window.alert('invald username or password');
      });
    }

when login() function is called, fetch() function throws this message in browser console. (http://localhost:4000/login) is server side and (http://localhost:8000) is client side.

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  <<-- fetch error message on browser console

I tried to fix it many different ways with no good outcome.

Goldsmith
  • 19
  • 2

1 Answers1

0

Try the following code:

import express from "express";
import http from "http";

const app = express();
const server = http.createServer(app);

const sio = require("socket.io")(server, {
    handlePreflightRequest: (req, res) => {
        const headers = {
            "Access-Control-Allow-Headers": "Content-Type, Authorization",
            "Access-Control-Allow-Origin": req.headers.origin, 
            "Access-Control-Allow-Credentials": true
        };
        res.writeHead(200, headers);
        res.end();
    }
});

sio.on("connection", () => {
    console.log("Connected!");
});
Rajind Pamoda
  • 123
  • 1
  • 10
  • I misguided you with commening socket.io. It had nothing to do with socket.io. Error was thrown by fetch() function. – Goldsmith Jan 12 '21 at 14:38