When the response header is 'Access-Control-Allow-Credentials,' it should be set to 'true' if the request's credentials mode is 'include'

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.

Answer №1

Give this code a try:

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!");
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with MomentJs: incorrect month displayed

Momentjs is displaying the wrong month. const time = moment("2300","hhmm").format("HH:mm"); const weekDay = moment().weekday(2).format("DD/MM/YYYY"); const notification = moment(weekDay + " " + time, "DD/HH/YYYY HH:mm"); console.log(notification); Expect ...

Unable to launch Google Maps in modal box

I want to implement loading the Google Maps .js API within a Bootstrap 3 modal box upon clicking a link, and then opening the modal box using the Google Maps initialize method. Here is an example of how this should work: HTML: <a data-toggle="modal" h ...

Multiple angularjs validations applied to a single textbox

Hello, I am currently working on an angularjs application where I have a textbox with a custom directive attached to it. This directive only accepts numbers within a certain range, for example between 100 to 200. The validation for this is working perfectl ...

Looking to navigate through a collection of objects using JavaScript

I'm seeking assistance with this code snippet I have written: const parqueAutomotor = []; parqueAutomotor[0] = {Brand: "Peugeot", Model: "206", Doors: 4, Price: &qu ...

Guide on wrapping text within a pie chart using d3 version 7.6.1 in conjunction with TypeScript

When attempting to create a pie chart, I came across two examples: one here https://bl.ocks.org/mbostock/7555321 and another here https://jsfiddle.net/05nezv4q/20/ which includes text. However, I'm working with TypeScript and D3 v7.6.1 and encounterin ...

Failed Axios POST request on iOS devices

Attempting a straightforward ajax POST from domain1 to domain2 using Axios. This involves a cross-domain simple POST without requiring a PREFLIGHT (OPTIONS) call. The response returned by the application is a basic JSON string. This process functions smoo ...

My React application is being loaded by Express regardless of the route I access. What could be causing this issue?

I'm struggling to access the json data located at /species because express always seems to load the react app regardless of the route I use. Can someone help me identify the issue? Here is an excerpt from my server.js file: const app = require(' ...

Execute a PHP POST request with dynamic value passing

Whenever I try to send two values, name and company, to the server, they always get passed as strings. app.post('/visitors/store', (req, res) => { const name = req.body.name; // User1 const company = req.body.company; // Google con.query("INS ...

Strategies for transferring a JavaScript variable from a JSP to a servlet

For my reporting module, I am utilizing the google visualization API java wrapper along with image charts. To pass the url of the generated chart to a servelet, I am using the getImageUrl() method to retrieve the url and storing it in a javascript variabl ...

Error: Unable to locate Buffer2

I encountered the error Uncaught TypeError: Buffer2 is undefined when trying to import jsonwebtoken into my React project. The errors occur with both import jwt from jsonwebtoken and import {decode} from 'jsonwebtoken'. My versions are jsonwebt ...

What steps are involved in developing a personalized service?

Below is the controller code: app.controller('myCtrl', function($scope, $http, $timeout) { $scope.getData = function() { $http.get("../send") .then(function(response) { $scope.text = response.data; $sc ...

How can I verify if the first character is a letter using express-validator?

case 'username': { return [ check( 'content.data.username', 'Username must contain at least one letter' ) // .matches('(?=.*[a-z])(?=.*[0-9])&apo ...

manipulating session variables with javascript ajax and php

I'm struggling with setting and retrieving session variables using JavaScript code that calls PHP functions via AJAX. I want to access the returned session field in my JavaScript, but nothing seems to be working. Can someone take a look at my code and ...

What causes an error when calling a method inside onSubmit?

Whenever I attempt to invoke the metetor method, I encounter an error stating "Uncaught TypeError: Meteor.call is not a function". Strangely enough, when I make the same call in a different file located at imports/api/some.js, it works perfectly fine. This ...

Is it possible to refresh resources in Node.js without the need to restart the server?

Is there a middleware or library that allows access to files added after the server starts without requiring a restart? I currently use koa-static-folder, but it seems unable to handle this functionality. ...

Angularjs: The Art of Loading Modules

I am facing an issue while trying to load certain modules. controller1.js: angular.module('LPC') .controller('lista_peliculas_controller', ['$scope', function($scope) { $scope.hola="hola peliculas"; }]); And ap ...

The error message reads: `'Icon' is not included in the export list of 'antd'`

I have recently developed a React application and I'm incorporating Ant Design (antd) into it. However, I encountered an issue in one of my project files where I am unable to use the Icon tag. It seems like this is a known problem in ANT V4. The impo ...

the sizing issue with three div elements

I am attempting to create 3 parallel divs in HTML. The middle div should be exactly 960px wide and centered on the page, with the left and right divs positioned on either side. The minimum width of the page is set to 1024px. When the browser width exceed ...

When the submit button is clicked on a React form, it not only submits the current form

I am working on a React application with multiple forms, where each form is rendered based on the current page index. I would like the "Next" button that retrieves the next component to also act as a submit button. The issue I am facing is that while the n ...

How can I configure express/fastify to allow for absolute path imports?

When working with Next.js, I was accustomed to importing ESM modules using import UserModel from "models/UserModel" without needing a prefix or extension like .js. To achieve this in other frameworks like express/fastify, you can refer to the doc ...