2024-01-21

Axios methods GET and POST do not respond in Vercel deploy

I have a MERN project in my Vercel account which is divided into two parts: client and server. Both pages are perfectly deployed and available but my Axios methods related to the server page don't work in my deploy when they do in my local PC. The only one that responds correctly is the hero, which brings me six images from my database and renders what I need. However, when I go into another route the browser console throws an error 500. For instance, I am in a route where I have an useEffect hook with an Axios POST method and I have no response from the server.

Axios from the front:

useEffect(()=>{
    async function getList(){
      try{
        const response = await axios.post("https://pelis-mern-server-five.vercel.app/lists/get-my-list", {id:user._id, profId:profileId}, {withCredentials:true, headers:{"Content-Type":"application/json"}})
        console.log(response)
        if(response.data.list.length > 0){
          console.log("hay")
          setList(response.data.list)
        }
      }catch(err){console.log(err.stack)}
    }
    getList()
  },[])

Controller from the back (route /lists/get-my-list):

const get_my_list = async (req,res) => {
    console.log("req.user", req.user)
    const {id, profId} = req.body
    const user = await User.findById(id)
    const index = user.profiles.findIndex(prof => prof._id == profId)
    const list = user.profiles[index].myList
    res.json({list:list})
}

This is what I obtain in my browser's console (my catch's console.log(err.stack)):

AxiosError: Request failed with status code 500
    at settle.js:19:12
    at XMLHttpRequest.f (xhr.js:111:7)

Axios also says that the error is BAD_RESPONSE, not BAD_REQUEST. The same error happens when I go into my dashboard with a GET method in an useEffect.

useEffect(()=>{
        async function obtainProfiles(){
            try{
                const data = await axios.get("https://pelis-mern-server-five.vercel.app/profiles",{withCredentials:true})
                console.log(data.data)
                setProfiles(data.data)
            }catch(err){
                console.log(err.stack)
            }
        }
        obtainProfiles()
},[])

From the back (route /profiles):

const get_all_profiles = async (req,res) => {
  console.log("req.user", req.user)
  let call = await User.findById({_id:req.user.id})
  let profiles = call.profiles
  res.json(profiles)
}

I check the logs in my server's deploy and this is the error that appears every time I don't have a response.

req.user undefined //user object console log

Unhandled Promise Rejection 
{"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"TypeError: Cannot read properties of undefined (reading 'id')",
"reason":{"errorType":"TypeError",
"errorMessage":"Cannot read properties of undefined (reading 'id')",
"stack":["TypeError: Cannot read properties of undefined (reading 'id')"," at get_all_profiles 
(/var/task/server/controllers/userControllers.js:68:48)","    at Layer.handle [as handle_request] 
(/var/task/server/node_modules/express/lib/router/layer.js:95:5)","    at next 
(/var/task/server/node_modules/express/lib/router/route.js:144:13)","    at Route.dispatch 
(/var/task/server/node_modules/express/lib/router/route.js:114:3)","    at Layer.handle [as handle_request] 
(/var/task/server/node_modules/express/lib/router/layer.js:95:5)","    at /var/task/server/node_modules/express/lib/router/index.js:284:15","    at Function.process_params 
(/var/task/server/node_modules/express/lib/router/index.js:346:12)","    at next 
(/var/task/server/node_modules/express/lib/router/index.js:280:10)","    at Function.handle 
(/var/task/server/node_modules/express/lib/router/index.js:175:3)","    at router 
(/var/task/server/node_modules/express/lib/router/index.js:47:12)"]},"promise":{},"stack":
["Runtime.UnhandledPromiseRejection: TypeError: Cannot read properties of undefined (reading 'id')","    at process.<anonymous> (file:///var/runtime/index.mjs:1276:17)","   
at process.emit (node:events:529:35)","    
at emit (node:internal/process/promises:149:20)","   
at processPromiseRejections (node:internal/process/promises:283:27)","    
at process.processTicksAndRejections (node:internal/process/task_queues:96:32)"]}

Unknown application error occurred

Runtime.Unknown

I think the main problem here is the user related to Passport's authentication. When I log in, the /signin route's log says that my user is authenticated and shows me the object but disappears when is redirected to the dashboard, making req.user undefined and not authenticated.

Why does this happens on Vercel when in my local host does work perfectly?

This is also my Passport strategy:

const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const User = require('../models/User')
const bcrypt=require('bcrypt')

module.exports.start = async(passport)=>{
  passport.use(new LocalStrategy({
    usernameField: 'email', 
    passwordField: 'password', 
  },
  async (email, password, done) => {

      try {
        const user = await User.findOne({ email });
        if (!user) {
          return done(null, false, { message: 'User not found' });
        }
         const isPasswordValid = await bcrypt.compare(password, user.password);
        
        if (!isPasswordValid) {
          return done(null, false, { message: 'ContraseƱa incorrecta' });
        }else{
          //console.log(user)
           return done(null, user);
        }
  
      } catch (error) {
        return done(error);
      }
    }
  ));
  
  passport.serializeUser((user, done) => {
    console.log("serialized", user)
    done(null, user._id);
  });
  
  passport.deserializeUser(async (id, done) => {
    console.log("deserialized")
    console.log(id)
    try {
      const user = await User.findById({_id : id});
      done(null, user);
    } catch (error) {
      done(error);
    }
  })
}

I call it in this way on index.js:

const passport = require('passport')
const local = require('./config/passport')
const flash = require('connect-flash')

local.start(passport)
app.use(passport.initialize())
app.use(passport.session())
app.use(flash())


No comments:

Post a Comment