app.post works, but router.post does not?

Viewed 282

I'm logging in on the front end with React. It goes to my node/Express/Passport Backend. Im able to log in successfully when it goes to the backend. but then im unable to communicate that back to the front end? I keep getting 404's and whatnot on the front end. I've tried everything, importing everything on the app.js (app.use) to the index.js (router.use) file. the only way i can get it to work is moving the router.post"login" to the app.js file and using it as a app.post, and then it only works when i put the route under the "app.use(routes)". My register post route works fine too, though. So im lost. I've delved into the cors and body parser stuff and the configs() and man, everything. its a deep deep rabbit hole. I need som e guidance here and explanation if thats ok. I've been working really hard on this and really need some mentor help here. I can include the passport middleware thats in another file, but i dont think thats the issue since im able to console.log ity logging me in at the end of the middleware, then console.logging in the last req res function. Thank you so much for helping!

p.s: Really the issue is "headers already sent", because when i try to sendStatus(200) in every which way possible, its not working (when the post route is "router.post". app.post works perfectly fine)

ps.s.s: youll probably see a lot of repeated and/or unneeded importing, but i dont want to fix that at the moment, that was just me trying every which way to get it to work. I can fix that later.

app.js

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const crypto = require("crypto");
const routes = require("./routes");
const connection = require("./config/database");
const cors = require("cors");
app.use(cors({ origin: "http://localhost:3001", credentials: true }));
const User = mongoose.models.User;

const bodyParser = require("body-parser");

const MongoStore = require("connect-mongo")(session);

require("dotenv").config();

app.use(express.json());

app.use(express.urlencoded({ extended: true }));

const sessionStore = new MongoStore({
  mongooseConnection: mongoose.connection,
  collection: "sessions",
});

app.use(
  session({
    secret: "zdfbdaf",
    resave: true,
    saveUninitialized: true,
    store: sessionStore,
    cookie: {
      cookie: { secure: false },
      maxAge: 1000 * 60 * 60 * 24,
    },
  })
);



require("./config/passport");

app.use(passport.initialize());
app.use(passport.session());

app.use(routes);
app.post(
  "/login",

  passport.authenticate("local"),
  (req, res) => {
    console.log("working");
    res.status(200).send();
  }
);

app.listen(3000);

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;
// cors is needed with router.use else you have to put routes on the app.js
// const cors = require("cors");
// router.use(cors({ origin: "http://localhost:3001", credentials: true }));
// const isAdmin = require("./authMiddleware").isAdmin;
router.use(bodyParser.urlencoded({ extended: false }));

/**
 * -------------- Post ROUTES ----------------
 *
 */

 router.post(
   "/login",

   passport.authenticate("local"),
  (req, res) => {
    console.log("working");
     res.sendStatus(200);
   }
 );

router.post("/register", (req, res) => {
  const saltHash = genPassword(req.body.repeatPassword);

  const salt = saltHash.salt;
  const hash = saltHash.hash;

  const newUser = new User({
    username: req.body.email,
    hash: hash,
    salt: salt,
  });

  newUser.save().then((user) => {});
  res.sendStatus(200);
});



module.exports = router;
1 Answers

Try to remove the app.post method call, and use this to define sub-router routes.

app.use('/', routes);

Currently, you have two handlers for the same route, that can cause bugs.

Related