Error while building my server [Route.get() requires a callback function] - node.js

I'm getting an error while building my server, which I have no idea how to fix. Any idea on how to fix this? Thank you! I'm attaching the server page but also my routes so you can see what I'm doing. The error is also listed below. Thank yo uso much!
Error:
users.post('/register' (req, res) => {
^^^^^^^^^
SyntaxError: Malformed arrow function parameter list
server.js
const express = require("express");
const cors= require("cors");
const bodyParser = require("body-parser")
const app = express();
const mongoose = require("mongoose");
const port = process.env.PORT || 5000
app.use(bodyParser.json())
app.use(cors())
app.use(
bodyParser.urlencoded({
extended: false
})
)
const mongoURI = ""
mongoose
.connect(mongoURI, {useNewUrlParser: true})
.then(() => console.log('Mongodb connected'))
.catch(err => console.log(err))
const Users = require('./routes/Users')
app.use('/users', Users)
app.listen(port, () => {
console.log('Server is running on pol.')
})
Here is more code from routes.
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();
const userData = {
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
password: req.body.password,
created: today
}
User.findOne({
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.export = users

Its a simple typo mistake
change
users.post('/register' (req, res) => {
TO
users.post('/register', (req, res) => {

Related

0 I am working on NodeJs application it's shop application. I am trying to save posts in database and I am getting this error after submitting form:

TypeError: Post is not a constructor
owoce.js
const express = require('express');
const router = express.Router();
const Post = require('../models/owoc');
router.get('/', (req,res) => {
res.send('we are on owoce');
//try {
// const owoce = await Owoc.find()
// res.json(owoce)
// }catch (err){
// res.status(500).json({ message: err.message })
// }
})
// router.get('/jablka', (req,res) => {
// res.send('we are on jablka');
//});
router.post('/', (req,res) => {
const owoc = new Post({
rodzaj: req.body.rodzaj,
kolor: req.body.kolor
})
owoc.save()
.then(data =>{
res.json(data);
})
.catch(err => {
res.json({message: err});
});
});
module.exports = router;
owoc.js it includes schema
const mongoose = require('mongoose');
const OwocSchema = new mongoose.Schema({
rodzaj: {
type: String,
required: true
},
kolor: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
//mongoose.Schema({
// username: String,
// password: String
//})
mongoose.exports = mongoose.model('Owoc', OwocSchema)
I am not sure what the problem is after looking at simmilar anwseres here
i dont see what should be changed
const Post = require('../models/owoc');
server.js adding it coz it may be usefull to troubleshoot
const express = require('express')
//const req = require('express/lib/request');
//const res = require('express/lib/response');
const app = express()
const mongoose = require('mongoose')
const bodyParser = require('body-parser');
require('dotenv/config');
app.use(bodyParser.json());
//const db = mongoose.connection('mongodb://localhost/sklep')
//MIDDLEWARES
app.use('/posts', ()=> {
console.log('This is a middleware');
});
//IMPORT ROUTES
const owoceRoute = require('./routes/owoce');
app.use('/owoce', owoceRoute);
//ROUTES
app.get('/', (req,res) => {
res.send('we are on home');
});
//connect to DB
mongoose.connect(
process.env.DB_CONNECTION ,mongoose.set('strictQuery', true), ()=> {
console.log('Connected to DB!!:))');
}); //{ useNewUrlParser: true})
//how to lisen to server
///db.on('error',(error) => console.error(error))
///db.once('open',() => console.log('connected to database'))
//db.on('connected', () => console.log('Connected to database'))
app.listen(3000, () => console.log('server started'))
I am adding screenshot and server code app despite not being sure if it will be any help
here is the screen from Postman
try this:
router.post('/create', async (req,res) => {
const owoc = await Owoc.create({
rodzaj: req.body.rodzaj,
kolor: req.body.kolor
})
.then(data =>{
res.json(data);
})
.catch(err => {
res.json({message: err});
});
});

That route does not exist! Getting a 404 error when making a sign up form

im trying to create a signup form by allowing users to enter in their email, password and name. I set up a 404 error code route when a route does not exist and for some reason its going off but i dont know for what reason. Can anyone detect the issue going on. I also have mongodb connected but im not sure if thats affecting it. Heres my code.
const { validationResult } = require('express-validator')
const User = require('../modelSchema/User')
const signUp = (req, res) => {
const errors = validationResult(req)
if(!errors.isEmpty()) return res.status(400).json({ errors: errors.array()})
//new instance of user
const user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password })
//save the user
user.save()
.then(data => {
response.json(data)
console.log(data)
})
.catch(err => {
response.json(err)
})
}
module.exports = { signUp }
heres my backend code where im importing mongodb and where my 404 error code is that detects a bad route
const express = require('express')
const cors = require('cors')
const app = express()
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const routes = require('./routes/index')
//middleware
app.use(cors())
dotenv.config()
mongoose.connect(process.env.DATABASE_ACCESS, () => console.log('Database Connected'))
//bodyParser
app.use(express.json({ extended: false }))
app.get('/', (req, res) => {
res.send('Hello World!');
})
app.all('*', (req, res) => res.send('That route does not exist!'))
app.use('/app', routes)
app.listen(4000, () => console.log('Server is listening on port 4000'))
heres where my routes are. for now i just have my signup route but later i will implement a login route
const express = require('express');
const { check } = require('express-validator')
const { signUp } = require('../controllers/users');
const router = express.Router();
router.post('/signup', [
check('name', 'Please Enter your Name').not().isEmpty(),
check('email', 'Please Enter your Email').isEmail(),
check('password', 'Please Enter your Password').isLength({ minLength: 6})
], signUp)
module.exports = router;
const signUp = (req, res) => {
const errors = validationResult(req)
if(!errors.isEmpty()) return res.status(400).json({ errors: errors.array()})
//new instance of user
const user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password })
//save the user
user.save()
.then(data => {
res.json(data)
console.log(data)
})
.catch(err => {
res.status(400).json(err)
})
}

OverwriteModelError: Cannot overwrite `user` model once compiled

I am facing this issue. I looked online for hours to find out what the problem is before posting here. I keep getting this error OverwriteModelError: Cannot overwrite ``user`` model once compiled. after sending a post request via postman and I can't find out what's going on. could you help me find out what's going on? thank you so much in advance!
server.js
const express = require("express");
const app = express();
const user = require("./routes/user");
const connectDB = require("./config/db");
connectDB();
app.use(express.json({extended: false}));
app.get("/", (req, res) => {
res.send("welcome to our api");
});
app.use("/user", user);
const PORT = 3000 || process.env.PORT;
app.listen(PORT, () => {
console.log(`PORT ${PORT} listening and refeshing...`);
});
db.js
const mongoose = require("mongoose");
const connectDB = () =>
mongoose
.connect(
"some database",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
)
.then(
() => {
console.log("mongoDB conneted");
},
(err) => {
console.log(err);
}
);
module.exports = connectDB;
user.js
const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const {body, validationResult} = require("express-validator");
router.get("/", (req, res) => {
res.send("hello");
});
router.post(
"/",
[
// password must be at least 5 chars long
body("email").isEmail(),
body("password").not().isEmpty(),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty) {
return res.status(400).json({errors: errors.array()});
}
try {
const UsersSchema = mongoose.Schema({
email: {type: String, required: true},
password: {type: String, required: true},
});
var users = mongoose.model("user", UsersSchema);
var user = new users({
email: req.body.email,
password: req.body.password,
});
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(req.body.password, salt);
user.save((err, user1) => {
if (err) {
console.log("error posing user");
throw err;
}
});
console.log(user.id);
const payload = {
user: {
id: user.id,
},
};
} catch (error) {
console.log(error);
res.status(400);
}
}
);
module.exports = router;
Every time the route runs it tries to create a schema which is already created.Mongoose create the collection with the first argument user by converting it to plural i.e. users.

User.find() returns empty response in mongodb express

I'm working with nextjs and express .I'm implementing simple signin form.I'm sending user credential and using find() ,checking whether user exist or not.but find() returns empty response.
In terminal find() returns array of that record.
model
const mongoose = require('mongoose')
const schema = mongoose.Schema
const user = new schema({
username: { type: String} ,
password: { type: String},
role: { type: String},
})
module.exports = mongoose.model('user', user);
router.js
const express = require('express')
const router = express.Router()
const user = require('../models/user');
router.post('/user/signin', (req, res) => {
user.find({
username: req.body.username, password: req.body.password
}, (err, user) => {
console.log(user);
if (err) {
result.status(404).send({ error: 'There is some error' });
} else if (user.length == 1) {
var token = 'kkl';//token
res.send({ token });
} else {
console.log(err);
res.send('Incorrect Email and Password');
}
});
})
module.exports = router;
this.is my index.js
const express = require('express')
const next = require('next')
const bodyParser = require('body-parser')
const PORT = process.env.PORT || 4000
const dev = process.env.NODE_DEV !== 'production' //true false
const nextApp = next({ dev })
const handle = nextApp.getRequestHandler() //part of next config
const mongoose = require('mongoose')
const router = express.Router();
nextApp.prepare().then(() => {
const app = express();
const db = mongoose.connect('mongodb://localhost:27017/knowledgeBase')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/knowledgeBase', require('./routes/router'));
app.get('*', (req, res) => {
return handle(req, res) // for all the react stuff
})
app.listen(PORT, err => {
if (err) {
console.log(err);
throw err;
}
console.log(`ready at http://localhost:${PORT}`)
})
})
please help
What response you get when you try this?
According to the response I will edit response.
router.post("/user/signin", async (req, res) => {
if (!req.body.username) return res.status(400).send("username cannot be null");
if (!req.body.password) return res.status(400).send("Password cannot be null");
const user = await User.findOne({ username: req.body.username});
if (!user) return res.status(400).send("User not found");
if (req.body.password!== user.password)
return res.status(400).send("Invalid password.");
res.send("logined");
});

Uncaught AssertionError: expected {} to equal 'testing'

I'm not sure why it's saying the object is empty. This is my testing block of code.
describe("POST /users", () => {
let body = {
name: "testing",
email: "testing#testing.com",
password: 123456
};
it("Creates a new user", done => {
request(app)
.post("/register")
.send(body)
.end((err, res) => {
if (err) return done(err);
expect(res.body).to.be.equal("testing");
done();
});
});
});
Is there something I'm missing for the test to recognize the information being passed in? As in the payload since I thought that is what .send(payload) was for.
Thanks for the clarity.
** Update Controller and more information **
// Testing
let request = require("supertest");
let expect = require("chai").expect;
let app = require("../../server/server");
describe("GET /test", function() {
it("Returns a json for testing", done => {
request(app)
.get("/test")
.end((err, res) => {
done();
});
});
});
describe("POST /users", () => {
let body = {
name: "testing",
email: "testing#testing.com",
password: 123456
};
it("Creates a new user", done => {
request(app)
.post("/register")
.send(body)
.expect(res => {
expect(res.body).to.be.equal("testing");
})
.end(done);
});
});
// User routes
const express = require("express");
const router = express.Router();
// Load User Model
const User = require("../../models/User");
// #route GET api/users/test
// #desc Tests user route
// #access Public
router.get("/test", (req, res) => res.json({ msg: "Users Works" }));
router.post("/register", (req, res) => {
User.findOne({ email: req.body.email }).then(user => {
if (user) {
res.status(409).json({ msg: "User exist" });
} else {
const newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password
});
newUser
.save()
.then(user => res.status(200).send(user))
.catch(err => console.log(err));
}
});
});
module.exports = router;
// Server
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
const users = require("./routes/api/users");
// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// DB Config
const db = require("../config/keys").mongoURI;
// Connect to MongoDB Atlas
mongoose.connect(
db,
{ useNewUrlParser: true },
(err, client) => {
if (err) {
console.log("Error occurred while connecting to MongoDB Atlas...\n", err);
}
console.log("Connected...");
}
);
// Routes
app.use("/api/users", users);
const port = process.env.PORT || 5000;
let server = app.listen(port, () =>
console.log(`Server running on port ${port}`)
);
module.exports = server;

Resources