I have some simple javascript code in three files. There is my server.js, which has
const userRouter = require('./routes/users') app.use("/",userRouter)
Then there is my middleware users.js with
module.exports = router
and lastly user.js with
module.exports = { User:User, validateLogin:validateUserLogin, validateRegister:validateUserRegister, }
When my user.js had just the export line module.exports = User
my code worked just fine. server.js imports users.js, which imports user.js. But when exporting functions along with my User object, my requests stop working. Why? How can I fix this? I’m using Node.js with express and mongo db. All my HTML requests are in users.js.
The code to my server.js is
const express = require('express'); const bodyParser = require("body-parser"); const mongoose = require("mongoose"); //just show server is running const app = express() app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); const PORT = 4000; app.get("/status", async (req, res) => { return res.status(400).send("server for GET is running"); }); app.post("/status", async (req, res) => { return res.status(200).send({ status: "server for POST is running", message: req.body.message }); }); app.listen(PORT, function() { console.log(`server running on port ${PORT}`); }); const url = "mongodb+srv://Admin:<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="631017110c0d0413021010140c110723000f1610170611534d170916020f4d0e0c0d040c07014d0d0617">[email protected]</a>/ConfusedTom?retryWrites=true&w=majority" mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true, dbName: "ConfusedTom" }).then(() => { console.log("connected successfully to server, using database %sn", mongoose.connection.$dbName); }).catch(err => { console.log(err); }); const userRouter = require('./routes/users') app.use("/",userRouter)
and here is my users.js
const mongoose = require("mongoose"); const express = require("express"); const router = express.Router(); const ObjectId = mongoose.Types.ObjectId; const Review = require("../models/review.js") const TVShow = require("../models/tvshows.js") const { User, validateLogin, validateRegister} = require("../models/user.js") router.get("/username", async (req, res) => { console.log("reached!") var user = await User.findOne({ username: req.body.username }); if (!user) return res.status(400).send("User doesn't exist."); return res.status(200).send(user) }); router.post("/register", async(req,res) => { const { error } = validateRegister(req.body); if (error) return res.status(400).send(error.details[0].message); else user = await User.findOne({ username: req.body.username }); if (user) return res.status(400).send("Username already taken."); //create new user user = new User({ firstName: req.body.firstName, lastName: req.body.lastName, username: req.body.username, password: req.body.password, }); user.save(); return res.status(200).send("User registered successfully."); }) router.post("/login", async (req, res) => { console.log("reached!") // validate the request body first const { error } = validateLogin(req.body); if (error) return res.status(400).send(error.details[0].message); //find an existing user var user = await User.findOne({ username: req.body.username }); if (!user) return res.status(400).send("Username reqired."); if (user) { if (user.validatePassword(req.body.password)) { return res.header.status(200).send("User login successfully"); } else return res.status(400).send("Password is incorrect"); } else return res.status(400).send("User doesn't exist."); }); module.exports = router
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The problem with your updated import of the stuff from user.js
is you’re using the wrong names for the functions. You currently have:
const UserStuff = require("../models/user.js") const User = UserStuff.User; const validateLogin = UserStuff.validateUserLogin; const validateregister = UserStuff.validateUserRegister;
but the object you’re exporting is:
module.exports = { User:User, validateLogin:validateUserLogin, validateRegister:validateUserRegister, }
You’re using the wrong names of the functions (validateUserLogin
instead of validateLogin
). The names you use have to match at both ends. So:
const UserStuff = require("../models/user.js") const User = UserStuff.User; const validateLogin = UserStuff.validateLogin; // ^^^^^^^^^^^^^ const validateregister = UserStuff.validateRegister; // ^^^^^^^^^^^^^^^^
or more concisely:
const { User, validateLogin, validateRegister} = require("../models/user.js")
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0