(NodeJS + Postman) cannot POST - node.js

i have been doing a postman POST request, but i got an error.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /bookstore</pre>
</body>
</html>
here is my POST request code:
app.post("/bookstore", (req, res) => {
const books = req.body;
db.collection("bookstore")
.insertOne(books)
.then((result) => res.json(result))
.catch((err) => res.send(err));
});
GET request is working normally, but when it came to POST, it is giving an error. Please fix my mistake! Thank you...
here is my full code:
db.js
const { MongoClient } = require("mongodb");
let dbConnection;
module.exports = {
connectToDb: (cb) => {
MongoClient.connect("mongodb://localhost:27017/bookstore")
.then((res) => {
dbConnection = res.db();
return cb();
})
.catch((error) => {
console.log(error);
return cb(error);
});
},
getDb: () => dbConnection,
};
and my index.js:
const express = require("express");
const { connectToDb, getDb } = require("./db");
const { ObjectId } = require("mongodb");
const e = require("express");
// init app and middleware
const app = express();
app.use(express.json());
//db connection
let db;
connectToDb((xato) => {
if (!xato) {
app.listen(3000, () => {
console.log("The 3000 port is installed");
});
db = getDb();
return db;
}
});
//routes
app.get("/bookstore", (req, res) => {
let mybook = [];
// the collection name from mongoDB
db.collection("bookstore")
.find()
.sort({ author: 1 })
.forEach((book) => mybook.push(book))
.then(() => {
return res.json(mybook);
})
.catch(() => {
return res.send("there were an error");
});
// res.json({ MyWords: "I am coming from json res" });
});
app.get("/bookstore/:id", (req, res) => {
if (ObjectId.isValid(req.params.id)) {
db.collection("bookstore")
.findOne({ _id: new ObjectId(req.params.id) })
.then((doc) => res.json(doc))
.catch((err) => res.send(err));
} else {
res.send(" wrong id request");
}
});
app.post("/", (req, res) => {
const books = req.body;
db.collection("bookstore")
.insertOne(books)
.then((result) => res.json(result))
.catch((err) => res.send(err));
});
I have restarted my express server, but it's still not working

Related

client.get("ping", (err, data) => in redis hangs my node js code

This is my server call to route
const redis = require("redis");
const client = redis.createClient();
client.connect();
module.exports = client;
This is my API route
app.get("/api/ping", middleWare.cacheRouteOne, RouteController.routeOne);
This is my cache route function
exports.cacheRouteOne = (req, res, next) => {
client.get("ping", (err, data) => {
console.log(data);//To check whether is working or not.
if (err) throw err;
if (data != null) {
res.json({
postss: JSON.parse(data),
});
} else {
next();
}
});
};
And this is my API call code
exports.routeOne = (req, res) => {
axios
.get("some APi CALL")
.then((response) => {
client.setEx("ping", 3600, JSON.stringify(response.data.posts));
console.log(client);
res.status(200).json({
status: true,
posts: response.data.posts,
});
});
};
When it calls the middle function it hangs my code after clinet.get()
I got the answer, I was making a call back but for forget to add await ,
so this is the updated middleware code
exports.cacheRouteOne = async (req, res, next) => {
let data = await client.get("ping");
console.log("data of ping");
if (data != null) {
res.json({
postss: JSON.parse(data),
});
console.log("yes");
} else {
next();
}
};
use this code to connect redis
const client = redis.createClient({
socket: {
port: 6379,
host: "127.0.0.1",
}
});
(async () => {
// Connect to redis server
await client.connect();
})();
console.log("Attempting to connect to redis");
client.on('connect', () => {
console.log('Connected!');
});
// Log any error that may occur to the console
client.on("error", (err) => {
console.log(`Error:${err}`);
});

node js : test rest API

i'm new learner in backend node js ... in my code below i created an API for questions and it contains get,post,delete and edit
i wanted to test it using the extension rest client in VS code but when i type Get http://localhost:3000/api in route.rest file to test it,it stucks on waiting
is there a way to know if my API works good and can somebody please help me if i have mistake below?
thanks in advance
//server.js
// #ts-nocheck
const express = require('express');
const morgan = require('morgan');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const jwt = require('jsonwebtoken');
const questionRoutes = require('./routes/subscribers');
const cors = require('cors');
const http = require('http');
// Has to be move but later
const multer = require("multer");
const Question = require('./models/subscriber');
// express app
const app = express();
// Explicitly accessing server
const server = http.createServer(app);
// corsfffffffff
app.use(cors());
dotenv.config();
const dbURI = process.env.MONGO_URL || "mongodb://localhost:27017/YourDB";
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(result => server.listen(process.env.PORT || 3000) )
.catch(err => console.log(err));
// register view engine
app.set('view engine', 'ejs');
app.use(express.json);
// middleware & static files
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.use(morgan('dev'));
app.use((req, res, next) => {
res.locals.path = req.path;
next();
});
// routes
// question routes
app.use('/questions' , questionRoutes );
// 404 page
app.use((req, res) => {
res.status(404).render('404', { title: '404' });
});
//questionRoute.js
const express = require('express');
const questionController = require('../controllers/questionCon');
const questionApiController = require('../controllers/questionApiController');
const router = express.Router();
// API Routing
router.get('/api/', questionApiController.get_questions);
router.post('/api/add', questionApiController.create_question);
router.get('/api/:id', questionApiController.get_question);
router.delete('/api/delete/:id', questionApiController.delete_question);
router.put('/api/update/:id', questionApiController.update_question);
// EJS Routing for GUI
router.get('/create', questionController.question_create_get);
router.get('/', questionController.question_index);
router.post('/', questionController.question_create_post);
router.get('/:id', questionController.question_details);
router.delete('/:id', questionController.question_delete);
module.exports = router;
//question.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const questionSchema = new Schema({
questionTitle: {
type: String,
required: true,
},
description: {
type: String,
},
price: {
type: Number,
},
});
const Question = mongoose.model('Question', questionSchema);
module.exports = Question;
//questionAPIcontroller
const Question = require('../models/subscriber');
const validators = require('../validators');
let questionApiController = {
// Get a single question
get_question : async (req , res) => {
const id = req.params.id;
try {
const question = await Question.findById(id,(err, question) => {
if (err) return res.status(400).json({response : err});
res.send("hello")
res.status(200).json({response : question})
console.log("hello")
})
} catch (err) {
res.status(400).json(err);
}
},
// Get all the questions
get_questions: async (req , res) => {
try {
const questions = await Question.find((err, questions) => {
if (err) return res.status(400).json({response : err});
res.status(200).json({response : questions})
})
} catch (err) {
res.status(400).json(err);
}
},
// Create a question
create_question : async (req , res) => {
const {error} = validators.postQuestionValidation(req.body);
if(error) return res.status(400).json({ "response" : error.details[0].message})
try {
const question = await new Question(req.body);
question.save((err, question) => {
if (err) return res.status(400).json({response : err});
res.status(200).json({response : " Question created Successfully"})
});
} catch (err) {
res.status(400).json(err);
}
},
// Delete question
delete_question : async (req , res) => {
const id = req.params.id;
var questionExist = false;
var userId ;
const question = await Question.findById(id).then(result => {
questionExist = true;
userId = result.owner;
}).catch(err => {
questionExist = false;
res.status(400).json({response : err });
});
if(questionExist){
try {
Question.findByIdAndRemove(id ,(err, question) => {
// As always, handle any potential errors:
if (err) return res.json({response : err});
// We'll create a simple object to send back with a message and the id of the document that was removed
// You can really do this however you want, though.
const response = {
message: "Question successfully deleted",
id: question._id
};
return res.status(200).json({response : response });
});
} catch (err) {
res.status(400).json(err);
}
}
else {
return res.status(400).send( { "response" : "A question with that id was not find."});
}
},
// Update question
update_question : async (req , res) => {
const id = req.params.id;
Question.findByIdAndUpdate(id,req.body,
function(err, result) {
if (err) {
res.status(400).json({response : err});
} else {
res.status(200).json({response : "Question Updated"});
console.log(result);
}
})
},
// Get question's questions
}
module.exports = questionApiController
//questionController
const Question = require('../models/subscriber');
const question_index = (req, res) => {
Question.find().sort({ createdAt: -1 })
.then(result => {
res.render('index', { questions: result, title: 'All questions' });
})
.catch(err => {
console.log(err);
});
}
const question_details = (req, res) => {
const id = req.params.id;
Question.findById(id)
.then(result => {
res.render('details', { question: result, title: 'Question Details' });
})
.catch(err => {
console.log(err);
res.render('404', { title: 'Question not found' });
});
}
const question_create_get = (req, res) => {
res.render('create', { title: 'Create a new question' });
}
const question_create_post = (req, res) => {
const question = new Question(req.body);
question.save()
.then(result => {
res.redirect('/questions');
})
.catch(err => {
console.log(err);
});
}
const question_delete = (req, res) => {
const id = req.params.id;
Question.findByIdAndDelete(id)
.then(result => {
res.json({ redirect: '/questions' });
})
.catch(err => {
console.log(err);
});
}
module.exports = {
question_index,
question_details,
question_create_get,
question_create_post,
question_delete
}
change code
app.use(express.json);
to
app.use(express.json());

axios call in react returns index.html

I am attempting to make an axios call inside of a useEffect hook, but all that is returned is the html.index file. I understand that express will direct any calls to "/" to index.html but i have specific routes established and other safeguards in place, so i dont know why this is happening...
React Component:
import React, { Fragment, useState, useEffect } from "react";
//uuid for card element key
import { v4 as uuidv4 } from "uuid";
import API from "../utils/API";
//dummy data
import books from "../dummy.json";
//import components
import Card from "../components/Card";
import Searchbar from "../components/Searchbar";
const Bookshelf = () => {
useEffect(() => {
loadBooks()
});
const loadBooks = () => {
API.getAllBooks().then(res => console.log(res))
}
const [bookArray, setBookArray] = useState({
books,
});
return (
<Fragment>
<div className="bookshelf">
<Searchbar />
<div className="bookshelf__heading__container">
<h2 className="bookshelf__heading">
Release the Kraken of Knowledge!
</h2>
</div>
<div className="bookshelf__container">
<section className="bookshelf__gallery">
{bookArray.books.map((book) => (
<Card
key={uuidv4()}
title={book.title}
author={book.author}
image={book.image}
/>
))}
</section>
</div>
</div>
</Fragment>
);
};
export default Bookshelf;
My Express Server:
const express = require("express");
const PORT = process.env.PORT || 3306;
const app = express();
const { sequelize } = require("./models");
const authors = require("./routes/authors");
const books = require("./routes/books");
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"))
}
app.use("/api/authors", authors);
app.use("/api/books", books);
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "../client/build/index.html"));
});
sequelize.sync().then(() => {
app.listen(PORT, () => {
console.log(listening on ${PORT});
});
});
Axios call:
import axios from "axios";
export default {
getAllBooks: function(){
return axios.get("/api/books/all");
}
};
My routes:
const express = require("express");
const router = express.Router();
const { Op, json } = require("sequelize");
const { Author, Book } = require("../models");
//POST new book:
router.post("/add_book", (req, res) => {
Book.create(req.body)
.then((book) => {
res.status(200).json({ book });
})
.catch((err) => {
res.status(500).send(err);
});
});
//PUT edit book by id:
router.put("/edit/:id", (req, res) => {
Book.update(req.body, {
where: {
id: req.params.id,
},
})
.then((numChanged) => {
res.status(200).json({ changedRows: numChanged[0] });
})
.catch((err) => {
res.status(500).send(err);
});
});
//GET all books;
router.get("/all", (req, res) => {
Book.findAll({
include: [Author],
})
.then((books) => {
res.status(200).json(books);
return json(books)
})
.catch((err) => {
res.status(500).send(err);
});
});
//GET books by title:
router.get("/title/:title", (req, res) => {
Book.findOne({
where: {
title: req.params.title,
},
include: [Author],
})
.then((books) => {
res.status(200).json(books);
})
.catch((err) => {
res.status(500).send(err);
});
});
//GET books by title OR author:
router.get("/search/:search_term", (req, res) => {
Book.findAll({
include: [Author],
where: {
[Op.or]: [
{ title: { [Op.substring]: req.params.search_term } },
{ "$Author.firstName$": { [Op.substring]: req.params.search_term } },
{ "$Author.lastName$": { [Op.substring]: req.params.search_term } },
],
},
})
.then((result) => {
res.status(200).json(result);
})
.catch((err) => {
res.status(500).send(err);
});
});
//DELETE book by id:
router.delete("/book_id/:id", (req, res) => {
Book.destroy({
where: {
id: req.params.id,
},
})
.then((wasDeleted) => {
res.status(200).json({ deleted: wasDeleted !== 0 });
})
.catch((err) => {
res.status(500).send(err);
});
});
module.exports = router;
I also have a proxy server set up and as far as i can tell thats working, but perhaps it might be related somehow...
Please let me know what else i can provide to help figure this out, its driving me up the wall.
EDIT: So if i make the call and include http://localhost:8080/etc, it works. That tell me there is (probably) a problem with the proxy server not working or express not finding it whatever...

Problem with saving information on mongodb

So I'm trying to set this form page, the information is being sent but the database is not being created automatically, and consequently, my info is not being saved
Sorry for the long post and thanks for any feedback
This is my app.js
mongoose.connect('mongodb://localhost/cloud', {
useNewUrlParser: true
})
})
.catch(err => console.log(err));
require('./models/post');
const post = mongoose.model('post');
const app = express();
app.post('/cloud', (req, res) => {
upload(req, res, (err) => {
if (err) {
res.render('index', {
msg: err
});
} else {
console.log(req.body);
const newUser = {
title: req.body.title,
}
new post(newUser).save().catch(post => {
res.redirect('/cloud');
})
}
});
});
app.get('/cloud', (req, res) => {
post.find({})
.sort({Date: 'desc'})
.then(posts => {
res.render('cloud/cloud', {
posts: posts
});
});
});
const port = 3000;
app.listen(port, () => {
console.log(`running ${port}`);
});
Schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const postSchema = new Schema ({
title:{
type: String,
required: true
}
});
mongoose.model('post', postSchema);
Handlebars file
{{#each posts}}
<h4>{{title}}</h4>
{{else}}
<p>No pics found</p>
{{/each}}
You did not specify your schema property at this line of your code.
new post(newUser).save().catch(post => {
res.redirect('/cloud');
The correct way is
new post({title: new User} ).save().catch(post => {
res.redirect('/cloud');
Now, you have specify mongoose to save a new record for title.

How to create a Mongo database to Node.js?

I have created the backend operations using Node.js / MongoDB and created services for them, but when I run the server it indicates that I've connected successfully, but I can't see a database in Robo 3T.
Here is what I coded:
DBConfig.js
var mongoose = require ('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
name : {
type : String,
require : true
},
address : {
type : String,
require : true
}
});
mongoose.model("User", UserSchema);
module.exports = mongoose;
mongoose.connect('mongodb://127.0.0.1:27017/TestDB4', function(err){
if(err)
{
console.log(err);
process.exit(-1);
}
console.log("Connected to the db")
});
I can't see an error. Why isn't the DB created?
check your User.Controller.js as this below,
var mongoose = require('../DBSchema/SchemaMapper');
var UserSchema = mongoose.model('User');
var UserController = function(){
this.insert = (data) => {
return new Promise((resolve, reject) => {
var user = new UserSchema({
userName: data.userName,
password: data.password
});
user.save().then(() => {
resolve({status: 200, message: "Added new user"});
}).catch(err => {
reject({status: 500, message: "Error:- "+err});
})
})
}
this.update = (id, data) => {
return new Promise((resolve, reject) => {
UserSchema.update({_id: id}, data).then(() => {
resolve({status: 200, message: "update user"});
}).catch(err => {
reject({status: 500, message: "Error:- " + err});
})
})
}
this.searchAll = () => {
return new Promise((resolve, reject) => {
UserSchema.find().exec().then((data) => {
resolve({status: 200, data: data});
}).catch(err => {
reject({status: 500, message: "Error:- " + err});
})
})
}
this.search = (id) => {
return new Promise((resolve, reject) => {
UserSchema.find({_id:id}).exec().then(user => {
resolve({status: 200, data: user});
}).catch(err => {
reject({status: 500, message: "Error:- " + err});
})
})
}
this.delete = (id) => {
return new Promise((resolve, reject) => {
UserSchema.remove({_id:id}).then(() => {
resolve({status: 200, message: "remove user"});
}).catch(err => {
reject({status: 500, message:"Error:- " + err});
})
})
}
}
module.exports = new UserController();
And User.Route.js as below,
var express = require('express');
var router = express.Router();
var Controller = require('./User.Controller');
router.post('/', (req, res) => {
Controller.insert(req.body).then(data => {
res.status(data.status).send({message: data.message});
}).catch(err => {
res.status(err.status).send({message: err.message});
})
});
router.put('/:id', (req, res) => {
Controller.update(req.params.id, req.body).then(data => {
res.status(data.status).send({message: data.message});
}).catch(err => {
res.status(err.status).send({message: err.message});
})
});
router.get('/', (req, res) => {
Controller.searchAll().then(data => {
res.status(data.status).send({data: data.data});
}).catch(err => {
res.status(err.status).send({message: err.message});
});
});
router.get('/:id', (req, res) => {
Controller.search(req.params.id).then(data => {
res.status(data.status).send({data: data.data});
}).catch(err => {
res.status(err.status).send({message: err.message});
});
});
router.delete('/:id', (req, res) => {
Controller.delete(req.params.id).then(data => {
res.status(data.status).send({message: data.message});
}).catch(err => {
res.status(err.status).send({message: err.message});
})
})
module.exports = router;
check your app.js as follows
const Express = require("express");
const BodyParser = require("body-parser");
const Routes = require("./Routes");
const Cors = require("cors");
const app = Express();
app.use(Cors());
app.use(BodyParser.urlencoded({ extended: false }));
app.use(BodyParser.json());
app.use('/', Routes);
app.listen(8083, 'localhost', (err) => {
if(err) {
console.log(err);
process.exit(-1);
}
console.log("Server listen port 8083");
});
and Routes.js as follows,
var Express = require("express");
var Routes = Express.Router();
var UserRoute = require('./src/User/User.Route');
var CommentRoute = require('./src/Comment/Comment.Route');
Routes.use('/user/', UserRoute);
Routes.use('/comment/', CommentRoute);
module.exports = Routes;

Resources