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;
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)
})
im trying to create a CRUD for my user, but i got a trouble when doing post request, i've seen some similar questions, but none are working for me
This is my userController
const { user } = require("../models");
exports.all = (req, res) => {
user.findAll().then((data) => {
res.send(data);
});
};
exports.findById = (req, res) => {
user.findByPk(req.params.id).then((data) => {
res.send(data);
});
};
exports.create = (req, res) => {
const newUser = {
id: user.length,
name: req.body.name,
email: req.body.email,
password: req.body.password,
username: req.body.username,
birth_date: req.body.birth_date,
phone_number: req.body.phone_number,
createdAt: new Date(),
updatedAt: new Date(),
};
if (!newUser.name ||
!newUser.email ||
!newUser.password ||
!newUser.username ||
!newUser.birth_date ||
!newUser.phone_number
) {
return res.status(400).json({ msg: "Please fill all the requirements" });
}
user.create(newUser).then((data) => {
res.send(data);
});
};
exports.update = (req, res) => {
const found = user.some((users) => users.id === parseInt(req.params.id));
if (!found) {
const updMmber = req.body;
user.forEach((users) => {
if (users.id === parseInt(req.params.id)) {
users.name = updMmber.name ? updMmber.name : users.name;
users.email = updMmber.email ? updMmber.email : users.email;
users.password = updMmber.password ? updMmber.password : users.password;
users.usersname = updMmber.usersname ?
updMmber.usersname :
users.usersname;
users.birth_date = updMmber.birth_date ?
updMmber.birth_date :
users.birth_date;
users.phone_number = updMmber.phone_number ?
updMmber.phone_number :
users.phone_number;
res.send("Users Updated", user);
}
});
} else {
res
.status(404)
.json({ msg: `No user found with the id of ${req.params.id}` });
}
};
exports.delete = (req, res) => {
const found = user.some((users) => id === parseInt(req.params.id));
if (!found) {
res
.status(404)
.json({ msg: `No user found with the id of ${req.params.id}` });
} else {
res.json({
msg: `User with id of ${req.params.id} has been deleted`,
user: user.filter((users) => user.id !== parseInt(req.params.id)),
});
}
};
exports.update = (req, res) => {
const found = user.some((users) => users.id === parseInt(req.params.id));
if (!found) {
const updMmber = req.body;
user.forEach((users) => {
if (users.id === parseInt(req.params.id)) {
users.name = updMmber.name ? updMmber.name : users.name;
users.email = updMmber.email ? updMmber.email : users.email;
users.password = updMmber.password ? updMmber.password : users.password;
users.usersname = updMmber.usersname ?
updMmber.usersname :
users.usersname;
users.birth_date = updMmber.birth_date ?
updMmber.birth_date :
users.birth_date;
users.phone_number = updMmber.phone_number ?
updMmber.phone_number :
users.phone_number;
res.send("Users Updated", user);
}
});
} else {
res
.status(404)
.json({ msg: `No user found with the id of ${req.params.id}` });
}
};
exports.delete = (req, res) => {
const found = user.some((users) => id === parseInt(req.params.id));
if (!found) {
res
.status(404)
.json({ msg: `No user found with the id of ${req.params.id}` });
} else {
res.json({
msg: `User with id of ${req.params.id} has been deleted`,
user: user.filter((users) => user.id !== parseInt(req.params.id)),
});
}
};
This is my user model
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class user extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
}
user.init({
name: DataTypes.STRING,
email: DataTypes.STRING,
password: DataTypes.STRING,
username: DataTypes.STRING,
birth_date: DataTypes.INTEGER,
phone_number: DataTypes.STRING,
}, {
sequelize,
modelName: "user",
});
return user;
};
This is my server.js
const express = require("express");
const app = express();
const PORT = 3000;
const userController = require("./controller/userController");
const addressesController = require("./controller/addressesController");
app.listen(PORT);
app.get("/", (req, res) => {
res.send("Hello World");
});
//user routes
app.get("/user", userController.all); // show Alldata user
app.get("/user/:id", userController.findById); // show data user :id
app.post("/user", userController.create); // create data user
app.post("/user/:id"); //update data user :id
app.delete("/user/:id"); //delete data user :id
This is the response when im trying to do a post request in postman
https://i.stack.imgur.com/vWnK5.png
Thank you so much for your help I really appreciate it!
You need to pass in a middleware to parse JSON requests in Express.
In Express 4.16+, the express.json() middleware is available:
const app = express();
app.use(express.json()); // add this
// routes, etc...
In Express 4.0 - 4.15, use the body-parser package:
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json()); // add this
// routes, etc...
In Express <4:
const app = express();
app.use(express.bodyParser()); // add this
// routes, etc...
the below code returns not found (404) all the time. But the console logs the data as expected.
I am using Node, Koa, and Mongoose.
the server.js
const Koa = require('koa');
const bodyparser = require('koa-bodyparser');
const UserRoutes = require('./router/user.routes');
const TrustRoutes = require('./router/trust.routes');
const auth = require('./middleware/auth');
const app = new Koa();
require('dotenv').config();
require('./db');
app.use(bodyparser());
app.use(auth);
app.use(
TrustRoutes.routes()
).use(TrustRoutes.allowedMethods());
app.use(
UserRoutes.routes()
).use(UserRoutes.allowedMethods());
app.listen(process.env.PORT || 3000);
trust.routes.js
const router = new Router({
prefix: '/trust'
});
router.get('/:trustId', async (ctx,next) => {
let id = ctx.params.trustId;
let trust = await Trust.findById(id);
console.log(trust);
ctx.response.body = {
status: true,
message: 'Trust info',
data: trust
};
console.log('trust info');
next();
});
module.exports = router
the console logs the below details
{
_id: new ObjectId("61ed34100ebd7c8fbdbef596"),
name: 'new trust',
description: 'match',
contact: { email: 'gmail#gmail.com', phone: '90334' },
isActive: true,
createdAt: 2022-01-23T10:55:12.866Z,
updatedAt: 2022-01-23T10:55:12.866Z,
__v: 0
}
trust info
and the middleware (I suspect in here)
require('dotenv').config();
const jwt = require("jsonwebtoken");
const User = require("../models/user")
const except = [
'/user/login'
];
const verifyToken = async (ctx, next) => {
if (except.indexOf(ctx.request.path) >= 0) return next();
let token = (
ctx.request.body.token || ctx.request.query.token ||
ctx.request.headers["authorization"]
);
if (!token) {
ctx.response.status = 403;
ctx.body = {
status: false,
message: 'Unauthorized'
}
return;
}
token = token.replace(/^Bearer\s+/,'');
try {
const decoded = jwt.verify(token, process.env.TOKEN_KEY);
const user = await User.findOne({
email: decoded.username
},{password: 0});
ctx.request.user = user;
} catch (err) {
ctx.response.status = 403;
ctx.body = {
status: false,
message: 'Unauthorized'
}
return;
}
next();
};
module.exports = verifyToken;
I know that something in here is not correct but hard to understand since it's my first time on these async and koa with middleware please help me out on this.
the postman
You don't export anything from your router-file. In order to use
app
.use(TrustRoutes.routes())
.use(TrustRoutes.allowedMethods());
you need to export the koa-router from the TrustRoutes-file:
const router = new Router({
prefix: '/trust'
});
router.get('/:trustId', async (ctx,next) => {
// ...
});
module.exports = router;
Apart from this when using async handlers, you need to either return next or await (see https://github.com/ZijianHe/koa-router/issues/476):
router.get('/:trustId', async (ctx,next) => {
// ...
return next(); // or await next();
});
I missed to have return next() in auth js the middleware.
After updating it next(); to return next() it works.
const verifyToken = async (ctx, next) => {
.....
return next();
};
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