skip to Main Content

I have deployed both client and server code on vercel. The registration of email id and other things are being sent from client side to server side and are stored in the database of MongoDB Atlas online. The problem occurs when I try to login with the credentials that I have registered with. The login credential gets checked, and as soon as the website loads to the next page after login, I am returned to login page and this error is shown on the console:

Access to fetch at 'https://swap-ease-now-backend.vercel.app/details' from origin 'https://swap-ease-now.vercel.app' 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'.
Details.js:9     GET https://swap-ease-now-backend.vercel.app/details net::ERR_FAILED
(anonymous) @ Details.js:9
f @ regeneratorRuntime.js:44
(anonymous) @ regeneratorRuntime.js:125
(anonymous) @ regeneratorRuntime.js:69
Be @ asyncToGenerator.js:3
o @ asyncToGenerator.js:22
(anonymous) @ asyncToGenerator.js:27
(anonymous) @ asyncToGenerator.js:19
(anonymous) @ Details.js:7
(anonymous) @ Details.js:32
as @ react-dom.production.min.js:244
ku @ react-dom.production.min.js:286
(anonymous) @ react-dom.production.min.js:282
w @ scheduler.production.min.js:13
P @ scheduler.production.min.js:14
Details.js:27 TypeError: Failed to fetch
    at Details.js:9:25
    at f (regeneratorRuntime.js:44:17)
    at Generator.<anonymous> (regeneratorRuntime.js:125:22)
    at Generator.next (regeneratorRuntime.js:69:21)
    at Be (asyncToGenerator.js:3:20)
    at o (asyncToGenerator.js:22:9)
    at asyncToGenerator.js:27:7
    at new Promise (<anonymous>)
    at asyncToGenerator.js:19:12
    at Details.js:7:20

I don’t know if the error is of cookies or tokens, or of cors because if the error was of cors, then it should not post the data also from client to server.

The server side code I have for app.js file is as follows:

const dotenv=require("dotenv");
const mongoose=require('mongoose');
const express=require('express');
const app=express();
const cors = require('cors');


dotenv.config({path: './config.env'});

const User=require('./models/userSchema');

require('./db/conn.js');
app.use(express.json());
app.use(cors());
// to link the router file to route the path easily
app.use(require('./router/auth'));

const PORT=process.env.PORT || 5000;
app.get('/signup',(req,res)=>
{
    res.send('Hello at signup');
})

app.listen(PORT,()=>
{
    console.log(`running at port number ${PORT}`);
})

And here’s the router’s auth.js file :

const jwt=require("jsonwebtoken");
const express=require('express');
const router=express.Router();
const bcrypt=require('bcryptjs');
const authenticate=require("../middleware/authenticate");
const fs = require("fs");
const path = require("path");
require('../db/conn');

const User=require('../models/userSchema');

const cookieParser = require("cookie-parser");
const cors = require("cors");
const Authenticate = require("../middleware/authenticate");
router.use(cookieParser());
router.use(cors());

//login route
router.post('/signin',async (req,res)=>
{
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'POST');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    try
    {
        let token;
        const {email,password}=req.body;
        if(!email || !password)
        {
            return res.status(400).json({error:"Either one or more fields are empty...."});
        }
        const userLogin=await User.findOne({email:email});
        if(userLogin)
        {
            const isMatch=await bcrypt.compare(password,userLogin.password);
            token=await userLogin.generateAuthToken();
            console.log(token);

            res.cookie("jwtoken",token,{
            expires: new Date(Date.now()+ 25892000000),
            httpOnly:true
            });
            if(!isMatch)
            {
                res.status(400).json({error:"Invalid user credentials...."});
            }
            else{
                res.json({message:"Successful"});
            }
        }
        else
        {
            res.status(400).json({error:"Invalid user credentials...."}); 
        }
        
    }
    catch(err){
        console.log(err);
    }

}
)

router.get('/details', authenticate,(req,res)=>
{
    res.send(req.rootUser);
})

2

Answers


  1. app.use(cors()); you should add cors options here. like this,

    app.use(cors({
       credentials: true, //if you are using authentication.
       origin: 'your domain url' // if line above is true, then this CANNOT be '*'
    }))
    

    to be more specific, in your case it will be this,

    const corsOptions = {
      origin: 'https://swap-ease-now.vercel.app',
      credentials: true,
    }
    
    app.use(cors(corsOptions))
    
    Login or Signup to reply.
  2. if you want set coockie need set credentialsoption in cors , and set orgin ,

    then in client most set credentials option to true in api

    app.use(
      cors({
        credentials: true,
        origin: "http://localhost:5173",
      })
    );
    

    in your controller for set coockie :

      return res
        .status(200)
        .cookie("userToken", userToken, {
          secure: "false",
          sameSite: "none",
        })
        .json({
          id: user._id,
          username,
          pic: user.pic,
        });
    

    in your clinet if you want work with api :

    axios.defaults.withCredentials = true;
    

    you can set this option in the fetch

    i hope this help .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search