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;
Related
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});
});
});
I have added a model to my frontend and backend so that users can update their profile (name age etc.), however, when I'm trying to update my test user name it's not updating, and I'm recieving the below error message in my terminalTerminal error
See below my server.js and profile.js
SERVER.JS
const express = require("express");
const bodyParser = require("body-parser");
const bcrypt = require("bcrypt-nodejs");
const cors = require("cors");
const knex = require("knex");
const register = require("./controllers/register");
const signin = require("./controllers/signin");
const profile = require("./controllers/profile");
const image = require("./controllers/image");
const { Pool } = require("pg");
const morgan = require("morgan");
const nodemailer = require("nodemailer");
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = "1";
const pool = new Pool({
connection: process.env.POSTGRES_URI,
ssl: process.env.DATABASE_URI ? true : false,
});
const db = knex({
client: "pg",
connection: process.env.POSTGRES_URI,
ssl: {
rejectUnauthorized: false,
},
});
const app = express();
app.use(bodyParser.json());
app.use(morgan("combined"));
app.use(cors());
app.get("/", (req, res) => {
res.send("it is working");
});
app.post("/signin", (req, res) => {
signin.handleSignin(req, res, db, bcrypt);
});
app.post("/register", (req, res) => {
register.handleRegister(req, res, db, bcrypt);
});
app.get("/profile/:id", (req, res) => {
profile.handleProfile(req, res, db);
});
app.post("/profile/:id", (req, res) => {
profile.handleProfileUpdate(req, res, db);
});
app.put("/image", (req, res) => {
image.handleImage(req, res, db);
});
app.post("/imageurl", (req, res) => {
image.handleApiCall(req, res);
});
app.post("/sendResetPassowrdLink", (req, res) => {
const email = req.body.email;
pool.query(`SELECT * FROM login WHERE email='${email}'`).then((data) => {
if (data.rowCount === 0) {
return res
.status(401)
.json({ message: "user with that email does not exists" });
}
const { email } = data.rows[0];
const emailBody = `your sever url is http://localhost:3001/resetpassword/${btoa(
email
)}`;
res.send(emailBody);
});
});
app.get("/resetpassword/:token", (req, res) => {
const email = atob(req.params.token);
const { newPassowrd, newPassowrdConfirm } = req.body;
if (newPassowrd !== newPassowrdConfirm) {
return res.status(400).json({ message: "passowrd does not match" });
}
const hash = bcrypt.hashSync(newPassowrd);
pool
.query(`UPDATE login SET hash='${hash}' WHERE email='${email}'`)
.then((data) => {
if (data.rowCount === 1) {
return res
.status(200)
.json({ message: "password updated successfully" });
}
});
});
const PORT = process.env.PORT || 3005;
app.listen(PORT, () => {
console.log(`app is running on port ${PORT}`);
});
PROFILE.JS
const handleProfile = (req, res, db) => {
const { id } = req.params;
db.select("*")
.from("users")
.where({ id })
.then((user) => {
if (user.length) {
res.json(user[0]);
} else {
res.status(400).json("not found");
}
})
.catch((err) => res.status(400).json("error getting user"));
};
const handleProfileUpdate = (req, res, db) => {
const { id } = req.params;
const { name, age, pet } = req.body.formInput;
db("users")
.where({ id })
.update({ name })
.then((resp) => {
if (resp) {
res.json("success");
} else {
res.status(400).json("Unable to udpate");
}
})
.catch((err) => console.log(err));
};
module.exports = {
handleProfile,
handleProfileUpdate,
};
I also recently added docker container to my backend and database, could that be the cause for the issue?
below is my github backend repo with the docker included
https://github.com/Moshe844/smartbrain-api/tree/master
Creating CRUD application. I am able to send GET requests, but other requests are not getting sent.
The below line is causing error.
await Book.create(req.body);
app.js
const express = require('express');
const connectDB = require('./config/db');
const books = require('./routes/api/book');
const app = express();
connectDB();
app.use('/api/books', books);
app.get('/', (req, res) => {
res.send('<h1>Starter Code</h1>')
});
const port = process.env.PORT || 8082;
app.listen(port, () => {
console.log(`Listening on port ${port}`);
})
routes/api/book.js
const express = require('express');
const router = express.Router();
// Load book model
const { Book } = require('../../models/Book');
// #route GET api/books/test
// #description tests books route
// #access Public
router.get('/test', (req, res) => {
res.send('Book route testing!');
});
// #route GET api/books
// #description get all books
// #access Public
router.get('/', async (req, res) => {
try {
const books = await Book.find();
res.json(books);
} catch (error) {
res.status(404);
res.json({nobooksfound: 'No Books found'});
}
});
// #route GET api/books/:id
// #description get single book by id
// #access Public
router.get('/:id', async (req, res) => {
try {
const book = await Book.findById(req.params.id);
res.json(book);
} catch (error) {
res.status(404);
res.json({ nobookfound: 'No Book Found' });
}
});
// #route POST api/books
// #description add or save book
// #access Public
router.post('/', async (req, res) => {
try {
await Book.create(req.body);
res.json({msg: 'Book added successfully'});
} catch (error) {
res.status(400);
res.json({
error: 'Unable to add this book'
})
}
});
// #route PUT api/books/:id
// #description update book
// #access Public
router.put('/:id', async (req, res) => {
try {
const book = await Book.findByIdAndUpdate(req.params.id, req.body);
res.json({
msg: 'Updated Successfully'
})
} catch (error) {
res.status(400);
res.json({
error: 'Unable to update the Database'
})
}
});
// #route PUT api/books/:id
// #description delete book
// #access Public
router.delete('/:id', async (req, res) => {
try {
const book = await Book.findByIdAndRemove(req.params.id, req.body);
res.json({msg: 'Book entry deleted successfully'});
} catch (error) {
res.status(404);
res.json({error: 'No such book'})
}
});
module.exports = router;
models/Book.js
const mongoose = require('mongoose');
const BookSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
author: {
type: String,
required: true
},
description: {
type: String
},
published_date: {
type: Date
},
publisher: {
type: String
},
updated_date: {
type: Date,
default: Date.now
}
});
module.exports = Book = mongoose.model('book', BookSchema);
Error is you have not used body-parser. Replace app.js code with the below one.
const express = require('express');
const bodyParser = require('body-parser');
const connectDB = require('./config/db');
const books = require('./routes/api/book');
let app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
connectDB();
app.use('/api/books', books);
app.get('/', (req, res) => {
res.send('<h1>Starter Code</h1>')
});
const port = process.env.PORT || 8082;
app.listen(port, () => {
console.log(`Listening on port ${port}`);
})
You are telling it to await. But await what. You must create a Promise to wait for.
Somewhere in you model you are going to need to create a Promise.
//here is an example so you can see the flow. I know it's mysql and not mongo, but a promise is a promis
pullWhiteList: async (phone) => {
data = new Promise((resolve, reject) => {
sql = "SELECT c.name AS client_name, w.* FROM api_whitelist w INNER JOIN api_client c ON w.client_id = c.client_id WHERE phone LIKE ? ORDER BY phone ASC LIMIT 10;";
db.query(sql, [phone + '%'], (err, res, fields) => {
if (err) {
resolve(err);
} else {
resolve(res);
}
});
})
return await data;
},
In my web app, I'm using express-jwt, but for some reason the secret refuses to be loaded and i do not understand why.
const express = require('express')
import { createClient } from "redis"
import { UserApi } from "./api/users"
const jwtExpress = require('express-jwt')
(async () => {
//load in dotenv
require('dotenv').config()
const app = express()
const client = createClient()
//Check redis
client.on('error', (err) => console.log('Redis Client Error', err))
//Connect to redis client
await client.connect()
//Create API instances
const ua = new UserApi(client)
//Initialize middleware
app.use(express.json())
app.use(jwtExpress({ secret: "test", algorithms: ['HS256']}).unless({path: ['/token', '/test']}));
//Create routes
//test
app.get("/test", function(req, res) {
res.send("got")
})
//signup - creates user
app.post("/signup", async function(req, res) {
const u = {email: req.body.email, password: req.body.password}
try {
const {token, refreshToken} = await ua.create(u)
res.send({token: token, refreshToken: refreshToken, user_email: u.email })
} catch (error) {
res.status(400).send({error: error.toString()})
}
})
//login - logs in user
app.post("/login", async function(req, res) {
const u = {email: req.body.email, password: req.body.password}
try {
const token = await ua.login(u)
res.send(token)
} catch (error) {
res.status(400).send({error: error.toString()})
}
})
//refresh - refreshes token
app.post('/refresh', async function (req, res) {
const u = {email: req.body.email, refresh: req.body.refreshToken}
try {
const token = await ua.token(u.email, u.refresh)
res.send(token)
} catch (error) {
res.status(400).send({error: error.toString()})
}
})
app.listen(3000, () => {
console.log("server up")
})
}) ()
Could the async function be a problem? This is a copy of the error I receive:
if (!options || !options.secret) throw new Error('secret should be set');
^
Error: secret should be set
at module.exports (C:\Users\user\Projects\music-app\backend\node_modules\express-jwt\lib\index.js:20:42)
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");
});