-1

Hello I am working on a school project and stuck, I am getting a cors error. I have used the loopback address as well as localhost. I have set the headers and installed cors. I have not tried the IP address but the front end is React on 3000 while the backend is express on 3001. Can anyone see what it is the I am doing wrong? I am getting the error....

localhost/:1 Access to fetch at 'http://localhost:3001/users/login' from origin 'http://localhost:3000' 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'.

This is the log in function.

const login = (e) => {
    e.preventDefault();
    let username = document.getElementById('loginusername').value;
    let password = document.getElementById('loginpassword').value;
    const body = `{ "loginusername" : "${username}", "loginpassword": "${password}" }`;
    console.log(body);
    fetch('http://localhost:3001/users/login', {
        method: 'POST',
        mode: 'cors',
        credentials: 'include',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: body,
    }).then((res) => {
        return res.json();
    }).then((res) => {
        if (res.status !== "success") {
            alert(`Error 1 : ${res.status}.`)
        } else {
            alert(`The user ${res.username} has been successfully created.`);
        }
        document.getElementById('loginusername').value = '';
        document.getElementById('loginpassword').value = '';
    }).catch((error) => {
        alert(`Error 2 : ${error}.`)
    })

}

This is the cors in app.js

var cors = require('cors');
app.use(cors({
  origin : [ 'http://localhost:3000' , 'http://localhost:3001' ],
  methods:["GET" , "POST" , "PUT", "DELETE"],
  credential: true
}));

This is the login route on the back end.

router.post('/login', (req, res) => {
  let returnResponce = ''; 

  users.findOne({
    where:
    {
      username: `${req.body.loginusername}`
    }
  }).then((nextThing) => {

    if (nextThing !== null) {
      if (nextThing.password == req.body.loginpassword) {
        if (req.session.viewCount) {
          req.session.viewCount += 1;
        } else {
          req.session.viewCount = 1;
        }
        req.session.authenticated = "true";
        req.session.username = req.body.loginusername;

        returnResponce = `{ "status" : "Logged In" }`;

      } else {

        returnResponce = `{ "status" : "Wrong password." }`;

      }
    } else {

      returnResponce = `{ "status" : "Wrong username." }`;

    }
  });

  res.setHeader('Access-Control-Allow-Origin', [ 'http://localhost:3000' , 'http://localhost:3001' ] );
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  res.setHeader('Access-Control-Allow-Credentials', 'true');

  res.write(returnResponce);
  res.end();

});
Phil
  • 157,677
  • 23
  • 242
  • 245
Harrison
  • 33
  • 4
  • Does this answer your question? [Allow multiple CORS domain in express js](https://stackoverflow.com/questions/26988071/allow-multiple-cors-domain-in-express-js) – Chemi Adel Sep 09 '21 at 23:50
  • The cors middleware config property you want is `credentials`. You have `credential`. See https://www.npmjs.com/package/cors#configuration-options. If you're using the cors middleware (recommended), you should not be manually setting `Access-Control-Allow-*` response headers – Phil Sep 10 '21 at 00:15
  • Also, you should never create JSON manually. I recommend `const body = JSON.stringify({ loginusername: username, loginpassword: password })` – Phil Sep 10 '21 at 00:23

1 Answers1

1

In this server-side code :

var cors = require('cors');
app.use(cors({
  origin : [ 'http://localhost:3000' , 'http://localhost:3001' ],
  methods:["GET" , "POST" , "PUT", "DELETE"],
  credential: true
}));

You're missing an "s". It's actually

{
  // ...
  credentials: true
}
Mouradif
  • 2,666
  • 1
  • 20
  • 37