1

Same as Title says, Why does my Get request sometimes work, but most of the time it 404's?

Been messing around with taking the "next()" out, but it doesnt matter same effect. Same with making the "res.json(req.user.firstName);" in the -----router.get("/user, auth, (req,res){})-----

module.exports.isAuth = (req, res, next) => {
  if (req.isAuthenticated()) {
    console.log(req.user);
    res.json(req.user.firstName);
     //next()
 
  } else {
    console.log("Nope");

    res
      .status(401)
      .json({ msg: "You are not authorized to view this resource" });
  }
};

when the get request DOES work, the log on the backend here ^^^^ gets logged twice, in 2 different ways like bwloe. nice/pretty and ugly.

{
  _id:  60e9fad2837ff62fcb580f27,
  username: 'drakecoleman@rocketmail.com',
  firstName: 'Drake',
  lastName: 'Coleman',
  hash: 'e017095b5684f72d88d9103f3a5df9dfbcb8fe23e823b6f0551a20151710721304b58cb02bc62b60098a383d0f573fdf5bcd30aa89a5b266db0d7aceb6d25656',
  salt: '7e040e90411d647200cc9cc120a1b3b182b035105ce3488fbcbfd39b56f44d9b',
  admin: true,
  __v: 0
}

{"_id":"60e9fad2837ff62fcb580f27","username":"drakecoleman@rocketmail.com","firstName":"Drake","lastName":"Coleman","hash":"e017095b5684f72d88d9103f3a5df9dfbcb8fe23e823b6f0551a20151710721304b58cb02bc62b60098a383d0f573fdf5bcd30aa89a5b266db0d7aceb6d25656","salt":"7e040e90411d647200cc9cc120a1b3b182b035105ce3488fbcbfd39b56f44d9b","admin":true,"__v":0}

When it 404's, the log only logs the ugly version of the user on the backend.

index.js

const router = require("express").Router();
const passport = require("passport");
const bodyParser = require("body-parser");
const genPassword = require("../lib/passwordUtils").genPassword;
const connection = require("../config/database");
const mongoose = require("mongoose");
const User = mongoose.models.User;

const isAuth = require("./authMiddleware").isAuth;


router.use(bodyParser.urlencoded({ extended: false }));
/**
 * -------------- GET ROUTES ----------------
 *
 */
router.get("/user", isAuth);

React Front End

user.js

import React from "react";
// import { Redirect } from "react-router-dom";

function UserProfile() {
  // if (props.auth === true) {
  //   return <Redirect to="/login" />;
  // } else {
  //   return <h1 className="red">Logged in </h1>;
  // }
  fetch("http://localhost:3000/user", {
    method: "GET",
    credentials: "include",
    withCredentials: true,
    headers: {
      "Content-Type": "application/json",
    },
  })
    .then((res) => res.json())
    .then((data) => console.log(data))
    .catch((err) => console.log(err));
  return <h1>Hello</h1>;
}

export default UserProfile;

This is in the console on the front end before the request, but i dont think its an issue since i get this on other routes with no issue "[HMR] Waiting for update signal from WDS..."

but I do get this error first on the front end console when it 404's

user.js:10 GET http://localhost:3000/user 404 (Not Found)

then after a few seconds I get (its also not typed in red background either, just white text)

TypeError: Failed to fetch user.js:10 Fetch failed loading: GET "http://localhost:3000/user".

Someone on the discord says to make sure I have the sessions initliazed and I do, on the app.js backend page. app.use(passport.initialize()); app.use(passport.session());

  • 1
    https://stackoverflow.com/questions/29111571/passports-req-isauthenticated-always-returning-false-even-when-i-hardcode-done This might have the answer you're looking for. – alex067 Jul 11 '21 at 18:45
  • yeah I already have it set up like that. Though switching the resave and saveuninitialized makes it work more often, but its still 50/50 on working/not working. – Drake Coleman Jul 11 '21 at 18:51
  • 1
    have you tried passing status in the GET response ? I see status is missing. Something like this:- res.status(200).json(req.user.firstName); and include the proper header as well. – Manish Kumar Jul 11 '21 at 19:20
  • that was an interesting find, but it didd not change anything. I am still learning web dev. I realize i should be putting the res.statuses more often. but to no avail this time. it didnt change anything. But it did make me notice i have to edit my post, because when it does work, it logs my user twice on the backend, one in the ugly way and one in the nice pretty way. and its the only console.log I have too. so im getting two consoles logs for only one input. – Drake Coleman Jul 11 '21 at 19:36
  • Can you try returning your res.json? return res.json(req.user.firstName); You don't need next() because your isAuth function is being treated as a route handler, and not a middleware. – alex067 Jul 11 '21 at 23:38
  • thank you so much for helping. I changed the isAuth to " if (req.isAuthenticated()) { return res.json(req.user.firstName);" and im still getting the same effects, where it works half the time, but other times it doesnt. I keep getting "SyntaxError: Unexpected end of JSON input at user.js:11" front end console error, and looking it up, im not experienced enough to understand what the issue is. (though now that issue is happening all the time, it use to only poop up as an error when the request worked.) – Drake Coleman Jul 12 '21 at 10:01
  • since I changed the isAuth, i then changed the front end fetch to ------------ .then((resp) => resp.text()) .then(console.log)--------------------------------- and same issue basically, where in the console I get back a string "Drake" but then sometimes I dont. – Drake Coleman Jul 12 '21 at 10:12

1 Answers1

0

Just found out the issue. Just goes to show you can never go wrong in showing all of your code. It ended up being my deSerialize user middleware. It was set up as

passport.deserializeUser((id, done) => {
  User.findById(id, (err, user) => {
    done(err, JSON.stringify(user));
  })
    .then((user) => {
      done(null, user);
    })
    .catch((err) => done(err));
});```

And when I changed to to this, my site worked 100%. 
passport.deserializeUser((id, done) => {
  User.findById(id, (err, user) => {
    done(err, user);
  })
    .then((user) => {
      done(null, user);
    })
    .catch((err) => done(err));
});

Forgive me to the people who helped who wasn't aware of this part of the code.