Node.js DELETE Request return wrong response - node.js

I'm making a DELETE request on my nodejs server, but the response is wrong.
When i try to send a DELETE request at my localhost server, it returns success: 0, message: "Record Not Found"
but when i go to check in the database, the parameters are gone
index.js
require("dotenv").config();
const express = require("express");
const app = express();
const userRouter = require("./api/users/user.router");
var cors = require('cors');
var corsOptions = {
origin: "http://localhost:3000"
};
app.use(cors(corsOptions));
app.use(express.json());
app.use("/api/", userRouter);
const port = process.env.PORT || 4000;
app.listen(port, () => {
console.log("server up and running on PORT :", port);
});
user.router.js
const router = require("express").Router();
const {
deleteUtenti
} = require("./user.controller");
router.delete("/", deleteUtenti);
module.exports = router;
user.controller.js
const {
deleteUtenti
} = require("./user.service");
module.exports = {
deleteUtenti: (req, res) => {
const data = req.body;
deleteUtenti(data, (err, results) => {
if (err) {
console.log(err);
return;
}
if (!results) {
return res.json({
success: 0,
message: "Record Not Found"
});
}
return res.json({
success: 1,
message: "user deleted successfully"
});
});
}
};
user.service.js
const pool = require("../../config/database");
module.exports = {
deleteUtenti: (data, callBack) => {
pool.query(
`delete from utenti where email = ?`,
[data.email],
(error, results, fields) => {
if (error) {
callBack(error);
}
return callBack(null, results[0]);
}
);
}
};
is it a problem of the code or of the server?
A few days ago the same thing happened to me with another function but to solve it was enough to recreate the table in the database, I tried to do the same thing but it didn't work

I Just found the problem, results[0] on user.service.js did not read the response from the database, so to do some tests I changed it to results where all the response from the database came out and I saw that I just had to take the affectedRows response from the database, so I changed it to results.affectedRows and now everything works as it should.

Related

postman when testing GET it returns 200 but with an empty body

When I m trying to test my GET API using postman it returns 200 but with an empty body, The data I'm expecting to get do not show up.
Find my server.js file and the screenshot of POSTMAN result
app.get('/api/articles/:name', async (req, res) => {
try {
const articleName = req.params.name;
const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true });
const db = client.db('my-blog');
const articleInfo = await db.collection('articles').findOne({ name: articleName })
res.status(200).json(articleInfo)
client.close()
}
catch (error) {
res.status(500).json({ message: 'error connecting to db', error })
}
})
here i have updated your code as below and please move your server.js outside of /src folder. its working now.
const express = require('express')
const bodyParser = require('body-parser')
const {MongoClient} = require("mongodb");
const url = 'mongodb://127.0.0.1:27017';
const app = express();
app.use(bodyParser.json());
app.get('/api/articles/:name', async (req, res) => {
try {
const articleName = req.params.name;
MongoClient.connect(url, async (err, db) => {
const client = db.db('article');
const articleInfo = await client.collection('articles').findOne({title: articleName})
res.send(articleInfo)
});
} catch (error) {
res.status(500).json({ message: 'Error connecting to db', error });
}
});
app.listen(8000, () => console.log('Listening on port 8000'));

POST request not coming through (MERN)

I'm using the MERN stack to build an application for the first time.
In order to log HTTP requests I use "morgan".
I managed to send data to mongodb which seems to be working fine. The problem is that my post request is not coming through. It says "pending" for 4 minutes, then fails.
Here's what I think is the relevant part of my code:
"server.js":
const express = require("express");
const mongoose = require("mongoose");
const morgan = require("morgan");
const path = require("path");
const cors = require("cors");
const app = express();
const PORT = process.env.PORT || 8080;
const routes = require("./routes/api");
const MONGODB_URI =
"...";
mongoose.connect(MONGODB_URI || "mongodb://localhost/app", {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on("connected", () => {
console.log("Mongoose is connected.");
});
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors());
app.use(morgan("tiny"));
app.use("/api", routes);
app.listen(PORT, console.log(`Server is starting at ${PORT}`));
Then I've put my routes into another file "api.js":
const express = require("express");
const router = express.Router();
const Lane = require("../models/lanes");
router.get("/", (req, res) => {
Lane.find({})
.then(data => {
res.json(data);
console.log("Get request successful!");
})
.catch(error => {
console.log("Error: ", error);
});
});
router.post("/save", (req, res) => {
const data = req.body;
const newLane = new Lane();
newLane.collection.insertMany(data, err => {
if (err) {
console.log(err);
} else {
console.log("Multiple docs inserted");
}
});
});
module.exports = router;
I'm using axios to send the request. This happens after submitting a form within my application.
reducer function:
const reducer = (state, action) => {
switch (action.type) {
case "add":
axios({
url: "http://localhost:8080/api/save",
method: "POST",
data: [...state, { id: uuid(), title: action.title, tasks: [] }]
})
.then(() => {
console.log("Data has been sent to the server");
})
.catch(() => {
console.log("Internal server error");
});
return [...state, { id: uuid(), title: action.title, tasks: [] }];
The reducer is being used by my context provider component, which looks like this:
export function LanesProvider(props) {
const [lanes, dispatch] = useReducer(reducer, defaultLanes);
return (
<LanesContext.Provider value={lanes}>
<DispatchContext.Provider value={dispatch}>
{props.children}
</DispatchContext.Provider>
</LanesContext.Provider>
);
}
The "add" method inside my reducer is being called when submitting a form inside another component.
Please let me know if I can add anything to my question that would help.
Thank you in advance!
you are not sending any response back to client. Try to modify post method like
router.post("/save", (req, res) => {
const data = req.body;
const newLane = new Lane();
newLane.collection.insertMany(data, err => {
if (err) {
console.log(err);
res.send(err)
} else {
console.log("Multiple docs inserted");
res.send("Multiple docs inserted")
}
});
});

Heroku - Request timed out for fetching request

On localhost:5000/posts my data is successfully showing but if I do the same thing in Heroku: https://rest-in-peep.herokuapp.com/posts I get an application error. https://rest-in-peep.herokuapp.com/ works fine and I deployed it through Heroku GIT. I made sure to config my environmental vars in Heroku and added a Procfile but I am still getting this application error. I've been trying all day to figure this out but what I expect to happen is if I type in https://rest-in-peep.herokuapp.com/posts, I will get all the data that is being stored on my MongoDB database.
app.js file
const http = require("http");
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
require("dotenv/config");
const app = express();
const server = http.createServer(app);
//Middlewares
app.use(cors());
app.use(bodyParser.json());
//Import Routes
const postsRoute = require("./routes/posts");
app.use("/posts", postsRoute);
//ROUTES
app.get("/", (req, res) => {
res.send("We are on home");
});
//Connect to DB
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true },
() => console.log("connected to MongoDB")
);
//How do we start listening to the server
server.listen(process.env.PORT || 5000, () => {
console.log("App now running on PORT");
});
routes>
posts.js
const express = require("express");
const Post = require("../models/Posts");
const router = express.Router();
//GETS BACK ALL THE POSTS
router.get("/", async (req, res) => {
try {
const posts = await Post.find();
res.json(posts);
} catch (err) {
res.json({ message: err });
}
});
//SUBMITS A POST
router.post("/", async (req, res) => {
console.log(req);
const post = new Post({
quote: req.body.quote
});
try {
const savedPost = await post.save();
res.json(savedPost);
} catch (err) {
res.json({ message: err });
}
});
//SPECIFIC POST
router.get("/:postId", async (req, res) => {
try {
const post = await Post.findById(req.params.postId);
res.json(post);
} catch (err) {
res.json({ message: err });
}
});
//Delete Post
router.delete("/:postId", async (req, res) => {
try {
const removedPost = await Post.remove({ _id: req.params.postId });
res.json(removedPost);
} catch (err) {
res.json({ message: err });
}
});
//Update a post
router.patch("/:postId", async (req, res) => {
try {
const updatedPost = await Post.updateOne(
{ _id: req.params.postId },
{
$set: { quote: req.body.quote }
}
);
res.json(updatedPost);
} catch (err) {
res.json({ message: err });
}
});
module.exports = router;
gitignore
/node_modules
models>Posts.js
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
quote: {
type: String,
required: true
}
});
module.exports = mongoose.model("Posts", PostSchema);

Http failure response for http://localhost:3003/register/registerObjectData/: 404 Not Found

I am creating a register page where i accept few details and store it in mongoDB. However, there must be some error which i am unable to follow. I am able to retrieve the data from the UI properly. And then i route this data via server.js to app.controller.js and from there to app.service.js.
I get error -
POST http://localhost:3003/register/registerObjectData/ 404 (Not Found)
And this is my code. Please help me figure out my mistake -
app.component.ts
register(registerData){
console.log("inside Register()");
this.registerObjectData = {
'userName': registerData.userName,
'email': registerData.email,
'firstPassword': registerData.firstPassword,
'repeatPassword': registerData.repeatPassword,
'phone': registerData.phone,
'company':registerData.company
}
this.http.post("http://localhost:3003/register/registerObjectData/"
, JSON.stringify(this.registerObjectData))
.map(Response => Response)
.catch((err) => {
console.log("err =", err)
return Observable.throw(err);
})
.subscribe((res: Response) => {
console.log("XXXXXXXXX Register Response ", res);
})
}
server.js
var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
//more definitions and var
app.listen(app.get('port'), function(){
console.log('Express server on port ' + app.get('port'));
});
app.use('/register', require('./api-mine-server/controller/register-
controller.js'));
app.controller.js
var express = require('express');
var router = express.Router();
var userService = require('../service/registerService');
var app = express();
router.post('/registerObjectData/:registerObjectData', registerUser);
module.exports = router;
function registerUser (req, res){
console.log("registerUser , BODY IS, JSON.parse,req ", JSON.parse(req.params.registerObjectData));
userService.registerUser(req,res)
.then(function (data) {
console.log("data after registration = ",data)
if(data == 'Registration Successful.'){
var set = {
data : data
}
res.send(set);
}
else{
res.send(data);
}
})
.catch(function (err) {
res.status(400).send('Something went wrong. Status 400');
});
}

Can't set headers after they are sent when using EventEmitter

Here is my code:
const cluster = require('cluster');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const queueMgr = require('./lib/queueManager');
const eventEmitter = new (require('events')).EventEmitter();
const app = express();
app.use(cors());
app.use((req, res, next) => {
if (channel) {
next();
}
queueMgr
.connect()
.then(ch => {
channel = ch;
next();
})
.catch(err => {
console.log(err);
res
.status(500)
.json({ message: 'Something Went Wrong' })
.end();
});
});
app.get('/', (req, res) => {
const taskId = Date.now() + '' + process.hrtime()[1];
const worker = queueMgr.launchWorker();
eventEmitter.once(taskId, msg => {
console.log(taskId);
res
.status(200)
.send({ message: msg, status: true })
.end();
});
queueMgr.addTaskToQueue(channel, config.taskQueueName, taskId, 'testmsg', 1000);
});
app.listen(PORT, () => {
console.log(`Process ${process.pid} listening on port ${PORT}`);
});
Here, for each GET / request, I create a unique taskId, attach it to the `eventEmitter.once. Then I attack it to a task queue.
Internally, I launch a worker to do the task then emit the taskId event, and on reciever, I send the response for that taskId.
Now, my first request works fine. However, my second and subsequest requests fail with the error
Error: Can't set headers after they are sent.
Be aware that next() function can be called two times.
Here
if (channel) {
next();
}
And then here
.then(ch => {
channel = ch;
next();
})
Maybe the second call of next() should not be done when the first one was called, if so, try to use return statement.
if (channel) {
return next();
}

Resources