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 )
Related
I am new to this and trying to create an rest Api using NodeJS, express and mongoose. after hitting postman, I only got id and version number but no other information.
i wrote this in postman body>raw with application/json
{
"name": "john cina",
"username": "cina",
"password": "abc123"
}
and may be after installing bcrypt, when I started my server its giving so many warnings like below:
(node:2400) Warning: Accessing non-existent property 'Symbol(Symbol.toStringTag)' of module exports inside circular dependency (Use node --trace-warnings ... to show where the warning was created) s inside (node:2400) Warning: Accessing non-existent property 'instanceOfSchema' of module exports inside circular dependency (node:2400) Warning: Accessing non-existent property '_id' of module exports inside circular depenircular ddency (node:2400) Warning: Accessing non-existent property '_id' of module exports inside circular dependency dency dency app listening at port 3000 connection successfull
my codes are below:
server file.
const express = require("express");
const mongoose = require("mongoose");
const userHandler = require("./routeHandler/userHandler");
const app = express();
app.use(express.json());
//connection
mongoose.set("strictQuery", true);
mongoose
.connect("mongodb://0.0.0.0/files", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("connection successfull"))
.catch((err) => console.log(err));
//application routes
app.use("/user", userHandler);
function errorHandler(err, req, res, next) {
if (res.headerSent) {
return next(err);
}
res.status(500).json({ error: err });
}
app.listen(3000, () => {
console.log("app listening at port 3000");
});
schema file.
const mongoose = require("mongoose");
const userSchema = mongoose.Schema({
name: {
type: String,
required: true,
},
username: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
status: {
type: String,
enum: ["active", "inactive"],
},
});
module.exports = userSchema;
userApifile.
const express = require("express");
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const router = express.Router();
const userSchema = require("../routeHandler/userHandler");
const User = new mongoose.model("User", userSchema);
router.post("/signup", async (req, res) => {
try {
const hashedPassword = await bcrypt.hash(req.body.password, 10);
const newUser = new User({
name: req.body.name,
username: req.body.username,
password: hashedPassword,
});
await newUser.save();
res.status(200).json({
message: "SIGN UP DONE",
});
} catch {
res.status(500).json({
message: "FAILED!",
});
}
});
module.exports = router;
Declare your model and export that in your schema file:
const User = new mongoose.model("User", userSchema);
module.exports = User;
Then, import it with:
const User = require('../path/to/user-schema.js);
To start with I am noob in node.js and MongoDb and working with tutorial with Lama Dev social media as a basic project kindly help
in Postman
error 404 is coming
where in the video it's 200 ok
I have copied main code for 100-1000 times help
This Is my auth.js file
//auth.js
const router = require("express").Router();
const User = require("../models/User");
//register
router.post("/register", async (req, res) =>{
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password,
});
try{
const user = await newUser.save();
res.status(200).json(user);
} catch(err) {
console.log(err);
}
});
module.exports = router;
This Is my User.js file in models folder
//User.js
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
username: {
type: String,
require: true,
min: 3,
max: 20,
unique: true,
},
email: {
type: String,
required: true,
max: 50,
unique: true,
},
password: {
type: String,
required: true,
min: 6,
},
profilePicture: {
type: String,
default: "",
},
coverPicture: {
type: String,
default: "",
},
followers: {
type: Array,
default: [],
},
followings: {
type: Array,
default: [],
},
isAdmin: {
type: Boolean,
default: false,
},
}, {timestamps: true});
module.exports = mongoose.model("User", UserSchema);
This Is my index.js file
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const helmet = require("helmet");
const morgan = require("morgan");
const userRoute = require("./routes/users");
const authRoute = require("./routes/auth");
dotenv.config();
mongoose.connect(process.env.MONGO_URL, ()=> {
console.log("MongoDb Connected");
});
//middleware
app.use(express.json());
app.use(helmet());
app.use(morgan("dev"));
app.use("/api/users", userRoute);
app.use("/api/auth", authRoute);
app.listen(8800, ()=>{
console.log("Backhend server is running");
})
And this is a screenshot of postman
Postman ScreenShot Click here
Your POSTMAN screenshot shows your HTTP verb being GET, but the route your registered is using POST. Try changing the verb in POSTMAN.
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.
I followed a tutorial and tried to implement some code from this repo https://github.com/ArjunAranetaCodes/MoreCodes-Youtube/tree/master/mern-mysql-login-reg. It takes a user's registration information and stores it in a database.
When I put in http://localhost:5000/users/register in postman I get a Cannot GET /users/register and I don't know why.
I don't know if its a problem with the database or not. I should be able to reach /users/register though shouldn't I?
server.js
const cors = require('cors');
const bodyParser = require('body-parser');
const express = require('express');
const port = process.env.PORT || 5000;
const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }))
const Users = require('./routes/Users');
app.use('/users', Users)
app.listen(port, () => {
console.log('SERVER RUNNING ON PORT: ' + port);
});
database/db.js
const Sequelize = require("sequelize")
const db = {}
const sequelize = new Sequelize("accounts", "root", "password", {
host: "localhost",
dialect: "mysql",
operatorAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
})
db.sequelize = sequelize
db.Sequelize = Sequelize
module.exports = db
models/User.js
const Sequelize = require('sequelize')
const db = require('../database/db.js')
module.exports = db.sequelize.define(
'user',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
email: {
type: Sequelize.STRING
},
username: {
type: Sequelize.STRING,
},
password: {
type: Sequelize.STRING,
},
name: {
type: Sequelize.STRING,
},
datetime: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
}
},
{
timestamps: false
}
)
routes/Users.js
const express = require('express')
const users = express.Router()
const cors = require('cors');
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt');
const User = require("../models/User")
users.use(cors());
process.env.SECRET_KEY = 'secret'
users.post('/register', (req, res) => {
const today = new Date().toDateString()
const userData = {
email: req.body.email,
username: req.body.username,
password: req.body.password,
name: req.body.name,
datetime: today
}
User.findOne({
where: {
email: req.body.email
}
})
.then(user => {
if (!user) {
bcrypt.hash(req.body.password, 10, (err, hash) => {
userData.password = hash
User.create(userData)
.then(user => {
res.json({ status: user.email + 'REGISTERED' })
})
.catch(err => {
res.send('ERROR: ' + err)
})
})
} else {
res.json({ error: "USER ALREADY EXISTS" })
}
})
.catch(err => {
res.send('ERROR: ' + err)
})
})
module.exports = users
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