cannot handle node JS delete request 404 error - node.js

it does give me back the id , but it is not deleting it from the mongodb collection & frontend list , I keep getting a 404 error on the network dev tools tab....
NodeJS
app.delete("/showlist-fromdb/:id", async (req, res) => {
try {
let uid = req.params.id.toString();
List.deleteOne({ _id: uid });
} catch (err) {
console.error(err);
}
});
React:
export const deleteListing = async (idHolder) =>{
/**DELETE METHOD */
const options = {
url: `http://localhost:5001/showlist-fromdb/:id${idHolder}`,
method: 'DELETE',
// data: idHolder
};
axios(options)
.then(response => {
console.log('A listing got deleted!')
}).catch((err)=>{console.log(err)})
// axios.delete(`http://localhost:5001/showlist-fromdb/:id${idHolder}`)
}

figured out the problem i forgot to add await before the delete command, thanks everyone

Related

Empty row on MongoDB data insertion using express.js

I want to add data to my MongoDB collection. I'm getting this data via a local Flask API. I'm GETting the data on my React Frontend and it's displaying fine. I'm not sure why I can't do the same thing on my express nodejs backend. I want to get that same data and use it to build the entity that I'm going to store.
This is how I'm attempting to get the data
app.get('/', async (req, res) => {
let initialData = {};
axios.get('http://localhost:3000/details').then((res) => {
initialData = res.data;
});
const recruit = new RecruitModel({ email:initialData.email,
mobile_number:initialData.mobile_number,
name:initialData.name});
try {
await recruit.save()
res.send("inserted data")
} catch (error) {
console.log(error)
}
})
I'm pretty sure something wrong there and nowhere else. Because if I pass static information instead it's correctly stored, no issues.
You are saving to the database's Recruit Collection before the promise is resolved. Since data to save in the Recruit Collection is dependent upon the result from the API which will initially return the promise, therefore, use promise resolving functions to wait for its result.
Solution#1 (using .then function):
app.get('/', async (req, res) => {
let initialData = {};
try {
axios.get('http://localhost:3000/details').then((response) => {
initialData = response.data;
const recruit = new RecruitModel({
email: initialData.email,
mobile_number: initialData.mobile_number,
name: initialData.name,
});
recruit.save().then((response) => res.send('inserted data'));
});
} catch (error) {
console.log(error);
}
});
Solution#2 (using async await keywords):
app.get('/', async (req, res) => {
try {
const response = await axios.get('http://localhost:3000/details');
const recruit = new RecruitModel({
email: response.data.email,
mobile_number: response.data.mobile_number,
name: response.data.name,
});
await recruit.save();
res.send('inserted data');
} catch (error) {
console.log(error);
}
});
Either solution will work in your case.

Hide api using expressjs and react

I'm using MERN stack for a project. I want to hide my api endpoints on the frontend when I call them. I'm now making a request from React like so:
useEffect(() => {
axios
.get("https://MY_API_URL/posts") // MY_API_URL is the url that I want to hide
.then((res) => {
dispatch(setCurrentUser(res.data));
})
.catch((err) => {
console.log(err);
});
});
This is how I'm GETing the posts from the expressjs:
controllers/posts.js
const Post = require("../models/post");
const getPosts = async (req, res) => {
try {
const post = await Post.find();
res.status(200).json(post);
} catch (err) {
res.status(404).json({ message: err });
}
};
I want to make the request to the url from the backend so that my API is hidden in the client.
This is what I have tried in the frontend:
useEffect(() => {
axios
.get("http://localhost:3000/posts")
.then((res) => {
dispatch(setCurrentUser(res.data));
})
.catch((err) => {
console.log(err);
});
});
And my backend now looks like this but it doesn't work. I also have removed the Posts.find() inside the request, I'm not sure if it is still necessary or how am I going to use this?
controllers/posts.js
const getPosts = async (req, res) => {
try {
const response = await axios.get(
"https://MY_API_URL/posts"
);
const posts = response.data;
console.log(posts);
res.status(200).json(posts);
} catch (err) {
res.status(404).json({ message: err });
}
};
On localhost it works fine, but when I push my code to github and deploy it, it doesn't work on the deployed version then in the localhost it also stops working.
Error message on console:
GET http://localhost:3000/posts 404 (Not Found)

Problems using React JS and WebSockets

I am learning about these technologies (React JS, Node, WebSockets) and working on a project that uses websockets to display information on graphs in real time.
I have a state in my component that stores an array of objects with different attributes.
When I make a POST request to my server the record is saved in the database (Made in PostgreSQL) and I notify the client to do the update
My problem is that when I refresh the page it stops working and I need to restart the server to be able to see the changes in the graph again.
SERVER
io.on('connection', client => {
app.post("/registros/nuevo", async (req, res) => {
try {
let insertar = await pool.query(`INSERT INTO registro
(fecha, hora, temperatura, presion, humedad, viento, viento_max, radiacion, precipitacion)
VALUES
('${req.body.fecha}', '${req.body.hora}', ${req.body.temperatura}, ${req.body.presion},
${req.body.humedad}, ${req.body.viento}, ${req.body.viento_max}, ${req.body.radiacion},
${req.body.precipitacion});`).then(() => { client.emit('new: data', 'updated') });
res.json({ message: "Recibido" });
} catch (err) {
console.error(err.message);
}
});
});
CLIENT
const [data, setData] = useState([])
const getData = async () => {
try {
const response = await fetch("http://localhost:5000/registros");
const jsonData = await response.json();
setData(jsonData);
setCurrent(jsonData[jsonData.length - 1])
} catch (err) {
console.error(err.message)
}
};
useEffect(() => {
getData()
}, [])
useEffect(() =>{
socket.on('new: data', (c) =>{
console.log(c)
getData()
})
}, []);
I know that my code isn't the best, and thank u for ur help
I got the solution, my mistake was put the request inside of socket body
app.post("/registros/nuevo", async (req, res) => {
try {
let insertar = await pool.query(`INSERT INTO registro
(fecha, hora, temperatura, presion, humedad, viento, viento_max, radiacion, precipitacion)
VALUES
('${req.body.fecha}', '${req.body.hora}', ${req.body.temperatura}, ${req.body.presion}, ${req.body.humedad}, ${req.body.viento}, ${req.body.viento_max}, ${req.body.radiacion}, ${req.body.precipitacion});`)
io.emit('new: data', 'Actualizado')
res.sendStatus(204)
} catch (err) {
res.sendStatus(500)
}
});

Cant Get My Data Deleted Properly From React-ExpressJS App CRUD Delete Request

I have managed to delete a query only with this code, but, it is not
deleting the query I clicked on, it deletes the query next to it with some kind of weird order...
I tried:
findByIdAndDelete(req.body.id); is not working!
findByIdAndDelete(req.params.id); is also not working!
Backend:
app.delete('/showlist-fromdb/:id', async (req, res) => {
try{
//was findOneAndRemove(req.body.title);
await List.findOneAndRemove(req.body.id);
return res.status(200).json({ success: true, msg: 'Product Deleted' });
}
catch(err){
console.error(err);
}
});
Frontend
export const deleteListing = async (idHolder) =>{
/**DELETE METHOD */
const options = await{
url: `http://localhost:5001/showlist-fromdb/:id${idHolder}`,
method: 'DELETE',
data: idHolder
};
axios(options)
.then(response => {
console.log('A listing got deleted!')
}).catch((err)=>{console.log(err)})
}

Can't get params from get request - Node JS, Angular

I have this angular method that gets features. I only need the features that have the releaseid that I pass with paramters.
getFeatures() {
this.route.params.subscribe(params => {
this.featureService.getFeatures(params['releaseid']).subscribe(res => {
this.features = res;
})
});
}
My service (featureService):
getFeatures(releaseId) {
const uri = 'http://localhost:4000/features';
return this
.http
.get(uri, {params: {releaseId: releaseId}})
.map(res => {
return res;
});
}
My nodejs route
featureRoutes.route('/features').get(function (req, res) {
console.log(req.body.params);
});
But the req.body.params is undefined.
Any help on this?
Try this
Service (featureService):
getFeatures(releaseId) {
const uri = 'http://localhost:4000/features?releaseId=' + releaseId;
return this.http.get(uri);
}
Nodejs route:
featureRoutes.route('/features').get(function (req, res) {
console.log(req.params); // should contain your releaseId
});
You should now be able to get the releaseId in your node backend.
I found it. in my routes i had to do:
console.log(req.query.releaseId)

Resources