Cannot fetch data from Nodejs backend to React frontend - node.js

I'm building MERN stack CRUD with goolge login
I'm running my server on port:3001
and frontend on port:3000
getAll() {
return axios.get("http://localhost:3001/jobs")
}
try to fetch data with session loggedin
router.get("/", util.isLoggedin, (req, res) => {
Job.find()
// .populate("author")
.limit(20)
.sort({ jobId: -1 })
.then((jobs) => res.json(jobs))
.catch((err) => res.status(400).json("Error:" + err))
})
const util = {}
util.isLoggedin = function (req, res, next) {
console.log(req.isAuthenticated())
if (req.isAuthenticated()) {
next()
} else {
console.log(req.isAuthenticated())
res.redirect("/")
}
}
module.exports = util
I can retrieve the data only on the server side, not frontend.
what can be the solution?
source code:
https://github.com/jamespark89/mern-communitywebsite

it seems like you are not awaiting your promise..
async getAll() {
return await axios.get("http://localhost:3001/jobs")
}

replace
getAll() {
return axios.get("http://localhost:3001/jobs")
}
with
async getAll() {
return await axios.get("http://localhost:3001/jobs")
}

Try to make your get request as an async function I usualy do that:
router.get("/", util.isLoggedin, async (req, res) => {
try {
const res = await Job.find()
// .populate("author")
.limit(20)
.sort({ jobId: -1 })
res.status(400).json({ res })
} catch(err) {
res.status(400).json("Error:" + err)
}
})

Related

modify query function in Sequelize

I'm learning "Sequelize".
I went through documentation and got this code somewhere else.
Model = require('../models/Salesman')
module.exports.creareSalesman = (req, res, next) => {
Model.create(req.body).then(
result => {
res.status.json({data: result})
}).catch(err => console.log(err))
}
but I want this in the below structure,
Model = require('../models/Salesman')
module.exports.creareSalesman = (req, res, next) => {
Model.create(req.body, function (result, err) {
if (err) {
console.log(err)
}
else {
res.status.json({data: result})
}
});
}
I tried this,.it didn't send the response. But inserted the data correctly to db.
How to get the response in this case.?
The Model.create method returns a Promise, and does not have a callback parameter.
So you either handle the Promise with then:
module.exports.creareSalesman = (req, res, next) => {
Model.create(req.body)
.then((result) => {
res.status.json({ data: result });
})
.catch((err) => console.log(err));
};
Or use async await:
module.exports.creareSalesman = async (req, res, next) => {
try {
const result = await Model.create(req.body);
res.status.json({ data: result });
} catch (err) {
console.log(err);
}
};

How to pass data from express-validation middleware to next function?

I have an express app that looks like this.
const app = require('express')();
// Task model
const Task = require('./models/Task');
const { param, validationResult } = require('express-validator');
const getTaskValidations = [
param('id')
.custom(async (id, { req }) => {
try {
const task = await Task.findOne({ _id: id, user: req.user.id });
if (!task) Promise.reject('Task not found');
} catch (err) {
// Handle error
}
})
]
const validate = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(401).json({ message: errors.array()[0].msg });
}
next();
}
// Get Task by id
app.get('/tasks/:id', getTaskValidations, validate, async (req, res) => {
try {
const task = await Task.findById(req.params.id);
res.json(task)
} catch (err) {
// Handle err
}
})
I want to get the task by id. In GET tasks/:id the req.params.id will contain the id of the task.
The Task Model looks like this
{
id:
task:
user:
}
By looking at the endpoint it is clear that I'm passing two middlewares.
The first middleware getTaskValidations will check if the task will given id and req.user exists.
The second middleware validate will check for errors.
And then again will query database for task and send data to the client causing 2 database queries.
How can I reuse the same task obtained in the getTaskValidations middleware.
you can add result of query add to the req.body.task like this
const getTaskValidations = [
param('id')
.custom(async (id, { req }) => {
try {
const task = await Task.findOne({ _id: id, user: req.user.id });
req.body.task = task
if (!task) Promise.reject('Task not found');
} catch (err) {
// Handle error
}
})
]
in controller
app.get('/tasks/:id', getTaskValidations, validate, async (req, res) => {
try {
let {task} = req.body
res.json(task)
} catch (err) {
// Handle err
}
})
You can store the response you get from the query in the request(req).
const task = await Task.findOne({ _id: id, user: req.user.id });
if (task)
req.task = task;
else
Promise.reject('Task not found');
Later on, in the API endpoint, you can simply use
app.get('/tasks/:id', getTaskValidations, validate, async (req, res) => {
try {
const task = req.task;
res.json(task)
} catch (err) {
// Handle err
}
});
to get the task obtained in the getTaskValidations middleware.

How to redirect/render to 404 if the "_id" is wrong/misspelled in /blogs/:blogId

I want to redirect users to "404.ejs" if the post id is entered wrong/mispelled in blogs/:blogId route. How can I accomplish it in below code.
app.get('/blogs/:blogid', (req, res) => {
const requestedId = req.params.blogid;
Blog.findById(requestedId, (err, addedblogpost) => {
if (err) {
console.log(err);
}
else {
res.render("post", {
title: addedblogpost.blogTitle,
content: addedblogpost.blogContent
})
}
})
}
Code for "404"
app.get('*', (req, res) => {
res.render('404');
})
You should make use of express next parameter to get the result you want.
This will call the next "matching" middleware for the current route, assuming this would be your error handler middleware of course.
It should be used as shown below :
app.get('/blogs/:blogid', (req, res, next) => {
const requestedId = req.params.blogid;
Blog.findById(requestedId, (err, addedblogpost) => {
if (err) {
next();
}
else {
res.render("post", {
title: addedblogpost.blogTitle,
content: addedblogpost.blogContent
})
}
})
Express doc : https://expressjs.com/en/guide/using-middleware.html
app.get('/blogs/:blogid', async (req, res) => {
const requestedId = req.params.blogid;
const blog = await Blog.findById(requestedId);
if (!blog) return res.render("404");
res.render("post");
}
to check if the blog is null or not.

Why does my register user post request fail with a 500 error?

I'm building an app with React and Node/Express, and I'm having trouble with my register user function. The data I am passing in is correct, and other endpoints work fine. The register one keeps returning a 500 error and I can't figure out why.
This is my request:
console.log(values)
axios
.post(
'https://foodtrackr-backend.herokuapp.com/api/register',
values
)
.then(res => {
console.log('res.data', res.data);
})
.catch(error => {
console.log('nope');
console.error(error);
});
};
and this is my endpoint:
router.post('/register', async (req, res) => {
let user = req.body;
const newUser = await Users.add(user);
try {
if (newUser) {
res.status(201).json(user);
} else res.status(404);
} catch (error) {
res.status(500).json('noooooo');
}
});
and this is my model:
function findById(id) {
return (
db('users')
.where({ id })
.first()
);
}
async function add(user) {
const [id] = await db('users').insert(user, 'id');
return findById(id);
}
Any help would be appreciated!

Subscribe method does not work in angular

product-operations.component.ts
deleteProduct() {
this.productsService.delete_product(this.deleteID).subscribe((res: any) => {
console.log("helloooooo");
});
};
product.service.ts
delete_product(id) {
return this.http.delete("http://localhost:3000/delete_product/" + id);
}
backend
exports.deleteProduct = (req, res, next) => {
const id = req.param("id");
Product.deleteOne({ _id: id })
.then(() => {
console.log("deleted");
})
.catch(err => {
console.log(err);
});
};
Problem:
In the above codes, the deleteProduct function in product-operations.component.ts doesn't work properly. More precisely, it does the removal. But after doing the uninstall, subscribe doesn't run its contents. This prevents my instant update after deletion. How can I solve this?
Try to send a response back from the server.
exports.deleteProduct = (req, res, next) => {
const id = req.param("id");
Product.deleteOne({ _id: id })
.then(() => {
res.send({}) // or res.send({id: id})
console.log("deleted");
})
.catch(err => {
res.status(500)
res.send({error: err})
console.log(err);
});
};

Resources