I am trying to send a post request and dealing with this error "Cannot POST /". What can be the problem? I am using a Postman to send a Post request to our server. My post request is
localhost:4000
Here is my index.js code:
const Joi = require('joi');
Joi.objectId = require('joi-objectid')(Joi);
const mongoose = require('mongoose');
const users = require('./routes/users');
const express = require('express');
const app = express();
mongoose.connect('mongodb://localhost/mongo-games')
.then(() => console.log('Now connected to MongoDB!'))
.catch(err => console.error('Something went wrong', err));
app.use(express.json());
app.use('/api/users', users);
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
And here is my user.js code:
const Joi = require('joi');
const mongoose = require('mongoose'); //needed for validation & creating user mongodb schema
const User = mongoose.model('User', new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
email: {
type: String,
required: true,
minlength: 5,
maxlength: 255,
unique: true
},
password: {
type: String,
required: true,
minlength: 5,
maxlength: 1024
}
}));
function validateUser(user) {
const schema = {
name: Joi.string().min(5).max(50).required(),
email: Joi.string().min(5).max(255).required().email(),
password: Joi.string().min(5).max(255).required()
};
return Joi.validate(user, schema);
}
exports.User = User;
exports.validate = validateUser;
And my users.js code:
const { User, validate } = require('../models/user');
const express = require('express');
const router = express.Router();
router.post('/', async (req, res) => {
// First Validate The Request
const { error } = validate(req.body);
if (error) {
return res.status(400).send(error.details[0].message);
}
// Check if this user already exisits
let user = await User.findOne({ email: req.body.email });
if (user) {
return res.status(400).send('That user already exisits!');
} else {
// Insert the new user if they do not exist yet
user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password
});
await user.save();
res.send(user);
}
});
module.exports = router;
What am I missing here? Any ideas?
Your middleware is- app.use('/api/users', users);
and your post is about that route.
In your postman> URL > you need to write localhost:4000/api/users.
because this is the URL that gets to the router.
Make sure that you are sending request to the /api/users. Looks like you are trying to send it to / which you are not handling.
Related
Please help review my error. I have defined my user schema but it is still undefined. I have spent hours on this error but I cannot seem to find where did I go wrong.
Here's my schema and model:
const { model, Schema } = require("mongoose");
const userSchema = new Schema({
username:String,
employeeId: String,
accessLevel: String,
role: String,
company: String,
password: String,
email: String,
createdAt: Date,
});
module.exports = model("User", userSchema);
Here's controller:
const User = require("../models/user");
const registerUser = (req, res, next) => {
let user = new User({
username: req.body.username,
employeeId: req.body.employeeId,
accessLevel: req.body.accessLevel,
role: req.body.role,
company: req.body.company,
password: req.body.password,
email: req.body.email,
createdAt: new Date(),
});
module.exports = {
registerUser
};
Here's connection to DB and server:
const express = require("express");
const mongoose = require("mongoose");
const { MONGODB } = require("./config");
const userRoute = require("./routes/userRouter");
const PORT = process.env.PORT || 4000;
mongoose
.connect(MONGODB, { useNewUrlParser: true, useUnifiedTopology: true })
.then(console.log("Database connected"))
.catch((err) => {
console.log(err);
});
const server = express();
server.use((err, req, res, next) => {
console.error(err);
res.status(err.statusCode).json(err);
});
server.use("/api/user", userRoute);
server.use(express.urlencoded({ extended: true }));
server.use(express.json());
server.listen(PORT, () => console.log(`Server is listening on ${PORT}`));
Here's router:
const express = require("express");
const usersControllers = require("../controllers/usersControllers");
const router = express.Router();
router.post("/registeruser", usersControllers.registerUser);
module.exports = router;
Post request on Postman: http://localhost:4000/api/user/registeruser
body:
{
"username": "Susan",
"employeeId": "12345",
"accessLevel": "Account Admin",
"role": "MC - Engineer",
"company": "Mello",
"password": "Choochootrain",
"email": "susan#hotmail.com"
}
Try to change the order of your middleware declarations:
const server = express();
server.use(express.urlencoded({ extended: true }));
server.use(express.json());
server.use("/api/user", userRoute);
server.use((err, req, res, next) => {
console.error(err);
res.status(err.statusCode).json(err);
});
my backend is running and im connected to mongoDB but when i send a post request from postman i get this error, i also put my network access to 0.0.0.0/0 (from anywhere) i have no idea by now what may cause this error.
this error is in my terminal:
Error: connect ETIMEDOUT 18.194.195.125:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1161:16) { name: 'MongoNetworkError' }
and i get this error in postman:
500Internal Server Error
this is my api index file:
const express = require("express");
const app = express();
const dotenv = require('dotenv');
const mongoose = require('mongoose')
const authRoute = require("./routes/auth");
dotenv.config();
app.use(express.json());
mongoose.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
}).then(console.log('Connected to MongoDB'))
.catch((err) => console.log(err));
app.use("/api/auth", authRoute);
app.listen("5000", () => {
console.log("Backend is running.");
});
and here is my auth file:
const router = require("express").Router();
const User = require("../models/User");
const bcrypt = require("bcrypt");
//REGISTER
router.post("/register", async (req, res) => {
try {
// making password hash
const salt = await bcrypt.genSalt(10);
const hashedPass = await bcrypt.hash(req.body.password, salt);
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: hashedPass,
});
const user = await newUser.save();
res.status(200).json(user);
} catch (err) {
res.status(500).json(err);
}
});
and my user file
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
unique: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
profilePic: {
type: String,
default: "",
},
},
{ timestamps: true }
);
module.exports = mongoose.model("User", UserSchema);
Check that your backend manages to connect to MongoDB.
Look for connection logs in your mongod terminal if you're running a server locally and check your connection string ( eg. mongodb://localhost:27017/db )
I can't find what I'm doing wrong. I already dug through a plethora of stacksoverflows but didn't find any solution.
I constantly getting MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms whenever I try to register a user. Some solutions say that I didn't connect to DATABASE. However, I get a confirm that the DB is connected successfully.
Here is the codes.
server.js
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const app = express();
const PORT = process.env.PORT || 5000;
// Init Middleware
app.use(express.json({ extended: false }));
app.use(cors());
// Bodyparser
app.use(express.urlencoded({ extended: false }));
// Connecting to mongoose
mongoose.connect(
process.env.REACT_APP_MONGO_URI,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
},
() => {
console.log("Connected successfully to DB!");
// Listening for actions
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
}
);
// Defined Routes
app.use("/", require("./routes/index"));
app.use("/users", require("./routes/users"));
users.js
const router = express.Router();
const bcrypt = require("bcryptjs");
const User = require("../models/User");
router.get("/login", (req, res) => {
res.send("Login");
});
router.get("/register", (req, res) => {
res.send("Register");
});
// #route POST /register
// #desc Creates a user
// #access Public
router.post("/register", async (req, res) => {
try {
const { name, surname, email, password, repeatedPassword } = req.body;
if (!name || !surname || !email || !password || !repeatedPassword) {
return res.status(400).json({ msg: "Not all fields were filled." });
}
if (password !== repeatedPassword) {
return res.status(400).json({ msg: "Password doesn't match." });
}
if (password.length < 6) {
return res
.status(400)
.json({ msg: "Password should be at least 6 characters long." });
}
/*
const user = await User.findOne({ email: email });
if (user) {
return res
.status(400)
.json({ msg: "This email is already specified by another user." });
}
*/
const newUser = new User({
name,
surname,
email,
password,
});
newUser.save();
console.log(newUser);
res.json(newUser);
} catch (error) {
res.status(500).send("Server error");
}
});
module.exports = router;
User.js (model)
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
surname: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = User = mongoose.model("User", UserSchema);
include user model and create one.
const User = require('./User')
await User.create({ name, surname, email, password, })
I have copied the code from another application, and that is working fine. but this one is giving me a Typeerror: cannot read property find of undefined when I am making the request to the database using the api.
here is my server.js
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");
const userRoutes = express.Router();
const PORT = 4000;
let { User } = require("./models/User");
app.use(cors());
app.use(bodyParser.json());
mongoose.connect("mongodb://127.0.0.1:27017/school", { useNewUrlParser: true });
const connection = mongoose.connection;
connection.once("open", function() {
console.log("MongoDB database connection established successfully");
});
userRoutes.route("/").get(function(req, res) {
User.find(function(err, users) {
if (err) {
console.log(err);
} else {
res.json(users);
}
});
});
app.use("/users", userRoutes);
app.listen(PORT, function() {
console.log("Server is running on Port: " + PORT);
});
here is my User Model:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
let User = new Schema({
firstName: {
type: String,
required: "First name is required"
},
lastName: {
type: String,
required: "Last name is required"
},
emailAddress: {
type: String,
required: "Email address is required",
match: [
/^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
"A valid email address is required"
]
},
password: {
type: String,
required: "Password is required"
}
});
module.exports = mongoose.model("User", User);
Your problem is the wrong way of importing User Schema , you can fix it like so :
let User = require("./models/User");
now your functions will work fine :)
I'm trying to set up an API with MongoDB (Mongoose) with a JWT authentication. I am at the first step where I create an user in the DB.
But I encounter a problem : the async/await taking so long and never ending, while the user is not created on DB. I don't know why.
I'm testing with POSTMAN for requests. For information, when I'm starting my app, I'm getting the "connected to db !" who appear correctly.
Can someone help me please ?
app.js
'use strict';
const express = require("express"),
app = express(),
authRoutes = require('./routes/auth'),
externalRoutes = require('./routes/web'),
database = require('./database/db'),
bodyParser = require("body-parser"),
mongoose = require('mongoose')
;
require('dotenv').config();
var options = { useNewUrlParser: true, useUnifiedTopology: true };
mongoose.connect("mongodb+srv://user:password#host.mongodb.net/test?retryWrites=true&w=majority", options, () => console.log('connect to db !'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/api/user', authRoutes);
app.use('/', externalRoutes);
app.listen(8080);
auth.js
const router = require('express').Router();
const User = require('../database/schemas/User');
router.post('/register', async (req, res) => {
const user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
});
const savedUser = await user.save((error, userDoc) => {
if (error) return res.status(400).send(error);
});
res.send({
user: savedUser._id
});
}).post('/login', (req, res) => {
});
module.exports = router;
User.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
min: 6,
max: 255
},
email: {
type: String,
required: true,
max: 255,
min: 10
},
password: {
type: String,
required: true,
max: 1024
},
createdAt: {
type: Date,
default: Date.now()
},
updatedAt: {
type: Date,
default: Date.now()
},
});
module.exports = mongoose.model('User', userSchema);
In Auth.js do this instead
const router = require('express').Router();
const User = require('../database/schemas/User');
router.post('/register', async (req, res) => {
const user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
});
try {
// if you are using await, don't pass it a callback
const savedUser = await user.save();
return res.send({
user: savedUser._id
});
} catch (error) {
// use try/catch to handle error instead of error first parameter in callback
return res.status(400).send(error);
}
}).post('/login', (req, res) => {
});
module.exports = router;
Here is a link to the documentation that shows you how to correctly use the save method. https://mongoosejs.com/docs/api.html#model_Model-save