I am very new to node.js/express/postman so please excuse me if this question is pretty rookie. I have the following code produced from following an online tutorial. I used Postman to test it. The problem is, when I add the line app.use(express.json), Postman is unable to send the post request. It gets stuck at "Sending request...". If I exclude that one line then the "Get" requests will work. Anyone know why... based on this code. This is all of it:
Thanks!
const Joi = require('joi'); // Put required modules at the top
const express = require('express');
const app = express();
app.use(express.json);
const courses = [
{ id: 1, name: 'course1' },
{ id: 2, name: 'course2' },
{ id: 3, name: 'course3' },
];
app.get('/', (req, res) => {
res.send('Hello world!!!');
});
app.get('/api/courses', (req, res) => {
res.send(courses);
});
app.post('/api/courses', (req, res) => {
const { error } = validateCourse(req.body);
if (error) return res.status(400).send(results.error.details[0].message);
const course = {
id: courses.length + 1,
name: req.body.name
};
courses.push(course);
res.send(course); // assigning the id on the server. return course to client
});
app.get('/api/courses/:id', (req, res) => {
const course = courses.find(c => c.id === parseInt(req.params.id))
if (!course) return res.status(404).send('The course with the given ID was not found');
res.send(course);
});
app.put('/api/courses/:id', (req, res) => {
const course = courses.find(c => c.id === parseInt(req.params.id))
if (!course) return res.status(404).send('The course with the given ID was not found');
const { error } = validateCourse(req.body);
if (error) return res.status(400).send(results.error.details[0].message);
course.name = req.body.name;
res.send(course);
});
app.delete('/api/courses/:id', (req, res) => {
const course = courses.find(c => c.id === parseInt(req.params.id))
if (!course) return res.status(404).send('The course with the given ID was not found');
const index = courses.indexOf(course);
courses.splice(index, 1);
res.send(course);
})
function validateCourse(course) {
const schema = {
name: Joi.string().min(3).required()
};
return Joi.ValidationError(course, schema);
}
// PORT
const port = 3000;
app.listen(port, () => console.log(`listening on port ${port}...`));
You're issue is the json middleware (app.use(express.json);), which requires you to return valid JSON (Content-Type: application/json).
I got your sample running, by updating it to the following:
app.get('/', (req, res) => {
res.json({msg: 'Hello world!!!'});
});
Here's a working version: https://pastebin.com/06H6LCD2
Try:
app.use(express.json({ extended: false }));
Related
Heroku routing does not work
here is my code,
when I deploy my local machine work The Heroku route does not work.
The home route is work but never works on the remote Heroku deployment route
I try to find my problem
tell me what to do
This indicates that the page exists but is producing some sort of error.. Any idea what could be happening? This is a very basic app that I built by reading the Rails Tutorial Book.
import express from "express"
import { MongoClient, ServerApiVersion } from "mongodb"
import { ObjectId } from "mongodb"
import cors from "cors"
import "dotenv/config"
const app = express()
app.use(cors())
app.use(express.json())
const PORT = process.env.PORT || 5000
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}#laptopstock.xnbrc.mongodb.net/myFirstDatabase?retryWrites=true&w=majority&ssl=true`
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1,
})
async function run() {
try {
await client.connect()
const laptopCollection = client.db("laptop_stock").collection("laptops")
app.post("/product", async (req, res) => {
const products = req.body
// console.log(products)
const NewProducts = await laptopCollection.insertOne(products)
res.send(products)
})
// get products
app.get("/product", async (req, res) => {
const query = {}
const cursor = laptopCollection.find(query)
const loadData = await cursor.toArray()
// console.log(loadData)
res.send(loadData)
})
app.get("/product/:id", async (req, res) => {
const id = req.params.id
const query = { _id: ObjectId(id) }
const service = await laptopCollection.findOne(query)
res.send(service)
})
app.put("/update/:id", async (req, res) => {
const id = req.params.id
const data = req.body
const filter = { _id: ObjectId(id) }
const options = { upsert: true }
const updateDoc = {
$set: {
productName: data.productName,
productQuantity: data.productQuantity,
productImg: data.productImg,
productDescription: data.productDescription,
productSeller: data.productSeller,
},
}
const updateProduct = await laptopCollection.updateOne(
filter,
updateDoc,
options,
)
res.send(updateProduct)
})
app.delete("/product/:id", async (req, res) => {
const id = req.params.id
const query = { _id: ObjectId(id) }
const deleteLaptop = await laptopCollection.deleteOne(query)
res.send(deleteLaptop)
})
} catch (error) {
console.log({ massage: error })
}
}
app.get("/", (req, res) => {
res.send({ message: "success" })
})
run()
app.listen(PORT, () => {
console.log("server is running port", PORT)
})
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());
I made an application to make push notifications and I succeeded in sending notifications. But I have a problem, which is that I want to save any notification that I send in my database,
Here is the code,
var FCM = require("fcm-node");
const express = require("express");
const mongoose = require("mongoose");
require("dotenv/config");
const app = express();
app.use(express.json());
const notificationSchema = mongoose.Schema({
name: String,
});
const NotificationModel = mongoose.model("Notification", notificationSchema);
app.post("/fcm", async (req, res, next) => {
try {
let fcm = new FCM(process.env.SERVER_KEY);
let message = {
to: req.body.token,
notification: {
title: req.body.title,
body: req.body.body,
},
};
fcm.send(message, function (err, response) {
if (err) {
next(err);
} else {
// res.json(response);
// res.send(message.notification.body);
app.post("/notfs", async (req, res) => {
let newNotf = new NotificationModel({
name: message.notification.body,
});
newNotf = await newNotf.save();
res.send(newNotf);
});
}
});
} catch (error) {
next(error);
}
});
app.get("/notfs", async (req, res) => {
const notfs = await NotificationModel.find();
res.send(notfs);
});
mongoose
.connect(process.env.CONNECTION_STRING)
.then(() => {
console.log("connected");
})
.catch((err) => {
console.log(err);
});
app.listen(3000, () => {
console.log("listened");
});
Why doesn't it save notifications in the database?
Another question
Please if there is a better way than this please leave it and thank you٫
Thanks in advance
use axios package, which is recommended by nodejs official.
Its simple like jquery ajax call
** trying to use the app.delete and trying to delete document from mondo db using delete one...it keep throwing errror. how to solve this error ? **
``` require('dotenv').config()
const express = require('express')
const app = express()
const PORT = process.env.PORT || 5001
const connectDB = require('./config/db')
const errorHandler = require('./middleware/error')
const Product =require('./models/product')
const cors = require('cors')
// Connect DB
connectDB()
// Middleware
app.use(cors())
app.use(express.json())
app.use('/auth', require('./routes/authRoutes'))
app.use('/admin', require('./routes/adminRoutes'))
app.use('/customer', require('./routes/customerRoutes'))
app.use('/staff', require('./routes/staffMemberRoutes'))
// error handler - should be *last* piece of middleware
app.use(errorHandler)
app.get('/all-products', (req, res) => {
Product.find({}, (error, posts) => {
if(error) {
res.json({error: 'Unable to fetch products!'})
} else {
res.json(posts)
}
})
})
app.post ('/add-products',(req,res) =>{
console.log("add-products has been fired")
const imageurl = req.body.imageurl
const title = req.body.title
const description = req.body.description
const rate = req.body.rate
const category = req.body.category
const subcategory = req.body.subcategory
let product = new Product({
imageurl: imageurl,
title: title,
description: description,
rate: rate,
category: category,
subcategory: subcategory,
})
product.save((error) => {
if(error) {
res.json({error: 'Unable to save the product!'})
} else {
res.json({success: true, message: 'New product Saved'})
}
})
})
app.delete('/product/:productId', (req, res) => {
const productId = req.params.productId
Product.deleteOne({
_id: productId
}, (error, result) => {
if(error) {
res.json({error: 'Unable to delete product'})
} else {
res.json({success: true, message: 'Product deleted successfully!'})
}
})
})
app.put('/update-product/:productId', (req, res) => {
const productId = req.params.productId
const imageurl = req.body.imageurl
const title = req.body.title
const description = req.body.description
const rate = req.body.rate
const category = req.body.category
const subcategory = req.body.subcategory
const updatedProduct = {
imageurl: imageurl,
title: title,
description: description,
rate: rate,
category: category,
subcategory: subcategory,
}
Product.findByIdAndUpdate(productId, updatedProduct, (error, result) => {
if(error) {
res.json({error: 'Unable to updated the Product'})
} else {
res.json({success: true, message: 'Product updated successfully!'})
}
})
})
const server = app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`)
})
// makes giant server errors concise and simple to read
process.on('unhandledRejection', (err, promise) => {
console.log(`Logged Error: ${err}`)
server.close(() => process.exit(1))
})```
if(error) {
res.json({error: 'Unable to delete product'})
}
In this line, replace res.json with:
res.json({error})
And then comment here the output (error message on the console)
I am making an app that saves and shows books to sell. It's everything ok, but this error began to appear:
GET http://localhost:3000/api/usuarios 404 (Not Found) zone-evergreen.js:2952
This error appears in two files: 'apuntes' and 'usuarios'
Here is the controller's code:
const usu = require('../models/usuario')
const usuarioCtrl = {};
usuarioCtrl.getUsuarios = async (req, res) => {
const usuarios = await usu.find();
res.json(usuarios);
}
usuarioCtrl.createUsuarios = async (req, res) => {
console.log(req.body);
const usuario = new usu({
nombre: req.body.nombre,
apellido: req.body.apellido,
fecha: req.body.fecha,
registro: req.body.registro,
password: req.body.password
});
await usuario.save();
res.json({
'status': 'Usuario Creado'
});
}
usuarioCtrl.getUsuario = async (req, res) => {
const usuarios = await usu.findById(req.params.id);
res.json(usuarios);
}
usuarioCtrl.editUsuario = async (req, res) => {
const { id } = req.params;
const usuario = {
nombre: req.body.nombre,
apellido: req.body.apellido,
fecha: req.body.fecha,
registro: req.body.registro,
password: req.body.password
};
await usu.findByIdAndUpdate(id, { $set: usuario }, { new: true });
res.json({ status: 'Usuario Actualizado' });
};
usuarioCtrl.deleteUsuario = async (req, res) => {
await usu.findByIdAndRemove(req.params.id);
res.json({ status: 'Usuario Borrado' });
}
module.exports = usuarioCtrl;
I'm sure that the index and route's code are right, but I don't know what to do and why this is happening. I have two controllers and two routes files and both have the same logic.
This is my first question in StackOverflow, I thank you for your help. If you need more details about the project, please tell me.
Here's the router:
const express=require('express');
const router1 = express.Router();
const ctrl1=require('../controllers/usuarios.controller');
router1.get('/', ctrl1.getUsuarios );
router1.post('/',ctrl1.createUsuarios);
router1.get('/:id',ctrl1.getUsuario);
router1.put('/:id',ctrl1.editUsuario)
router1.delete('/:id',ctrl1.deleteUsuario);
module.exports=router1;