data will not goto backend in mongodb using vue.js - node.js

backend will work when i using postman but when i using frontend for storing data only id will goes to database
here my frontend code where i declare method:-
methods: {
feedbackData() {
let KisanData1 = {
name1: this.name1,
village: this.village
};
console.log(KisanData1);
axios
.post('http://localhost:3000/User', KisanData1)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
}
backend code where i insert data:-
app.post('/User', (req, res) => {
console.log(req.body);
User.create(req.body).then((message) => {
res.json(message);
}).catch((error) => {
res.status(500);
res.json(error);
});
});
and create method in mongodb:-
function create(message) {
const result = Joi.validate(message, UserSchema);
if (result.error==null) {
message.created = new Date();
return info.insert(message);
} else {
return Promise.reject(result.error);
}
}

Related

Cannot Getting data from url query parameters. from a node rest api

I have this code to make a get, post, put and delete request,
const express = require("express");
const TutorialModel = require("../models/tutorialModel");
const router = express.Router();
router.post("/tutorials", async (req, res) => {
try {
const tutorial = new TutorialModel(req.body);
const createTutorial = await tutorial.save();
res.status(201).send(createTutorial);
} catch (e) {
res.status(400).send(e);
}
});
router.get("/tutorials", async (req, res) => {
try {
const TutorialsData = await TutorialModel.find();
res.status(200).send(TutorialsData);
} catch (e) {
res.status(404).send(e);
}
});
router.get("/tutorials/:id", async (req, res) => {
try {
const _id = req.params.id;
const TutorialData = await TutorialModel.findById(_id);
if (!TutorialData) {
res.status(404).send();
} else {
res.send(TutorialData);
}
} catch (e) {
res.status(500).send(e);
}
});
router.get("/tutorials/:title", async (req, res) => {
try {
const _title = req.params.title;
const TutorialData = await TutorialModel.find({ title: _title });
if (!TutorialData) {
res.status(404).send();
} else {
res.send(TutorialData);
}
} catch (e) {
res.status(500).send(e);
}
});
router.put("/tutorials/:id", async (req, res) => {
try {
const _id = req.params.id;
const updateTutorial = await TutorialModel.findByIdAndUpdate(
_id,
req.body,
{ new: true }
);
res.send(updateTutorial);
} catch (e) {
res.status(400).send(e);
}
});
// Deleting student data by its Id
router.delete("/tutorials/:id", async (req, res) => {
try {
const _id = req.params.id;
const deleteTutorial = await TutorialModel.findByIdAndDelete(_id);
if (!_id) {
return res.status(400).send();
} else {
res.send(deleteTutorial);
}
} catch (e) {
res.status(500).send(e);
}
});
router.delete("/tutorials", async (req, res) => {
try {
const deleteTutorial = await TutorialModel.remove();
if (!deleteTutorial) {
return res.status(400).send();
}
else {
res.send(deleteTutorial);
}
} catch (e) {
res.status(500).send(e);
}
});
module.exports = router;
I've successfully made all request including get request with 'id' But when I try to make get request using 'title' parameter I'm getting data of get request of "/tutorials" not of "tutorials/:title". What is the issue? Can anyone tell me please?
The route GET "/tutorials/:id" will catch all your GET requests like /tutorials/something. It does not distinguish if you pass an id or a title.
:id is used to tell Express to capture the something path in the URL in req.params.id. That's all.
If you want to have another route to get tutorials by title, you should use another form. For example, GET "/tutorialsByTitle/:title".

Cannot get data from backend while updating

Here's the code in react that I am using to get the data from database.
const getData = async (e) => {
const res = await fetch(`${process.env.REACT_APP_BASE_URL}/edit/${id}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
const data = await res.json();
console.log(data);
if (res.status === 422 || !data) {
console.log("Error");
} else {
setValues(data);
console.log("Data Edited successfully");
}
};
useEffect(() => {
getData();
}, []);
Here's the patch request
router.patch("/edit/:id", async (req, res) => {
try {
const { id } = req.params;
const updateUser = await Crud.findByIdAndUpdate(id, req.body, {
new: true,
});
console.log(updateUser);
res.status(201).json(updateUser);
} catch {
res.status(422).json(error);
}
});
I want to update the data in my application but I cannot get the data from the database. So can anyone tell what the problem is
From frontend, you are calling GET request and from your backend, you're receiving as a patch how it works pls do the same method on both hands

React - delete request come with error code 404

I've an issue while i'm trying to delete a driver from mySQL db.
Calling my function and passing mapped id (it's working):
<button id="deleteRent" onClick={DeleteVehicles.bind(vehicle.id)}>Delete</button>
Here is my react code:
const DeleteVehicles = (CarId) => {
Axios.delete(`http://localhost:3001/vehicleDelete/${CarId}`)
.then((response) => {
if (response) {
console.log(response)
alert("Sikeres Törlés")
navigate("/admin");
}
else {
console.log("törlési hiba")
}
})
}
and here is my node express request:
app.delete('/vehicleDelete/:CarId'), async (req, res) => {
db.query("DELETE FROM products WHERE id = ?", req.params.CarId,
(err, result) => {
console.log(err)
console.log(result)
if (result) {
res.send(result);
}
})
}
any idea?
axios should be lowercased:
axios.delete(`http://localhost:3001/vehicleDelete/${CarId}`)
Be careful with the closing parentheses on the express code:
app.delete('/vehicleDelete/:CarId', async (req, res) => {
db.query("DELETE FROM products WHERE id = ?", req.params.CarId, (err, result) => {
if (err) return res.status(500).send('Error')
res.status(200).send(result);
})
})
You should run this:
app.delete('/vehicleDelete/:CarId'), (req, res) => {
// make sure your are getting CarId that exists
// and then you delete it
db.query(`DELETE FROM products WHERE id = ${req.params.CarId}`,
(err, result) => {
console.log(err)
console.log(result)
if (result) {
res.send(result);
}
})
}
Also, you don't need to add async as your not using await for the query. The result gives you an object that might look like this:
{
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
Now, when you say you receive the 404 status code, it means that you don't have the route on which the request is made. So, http://localhost:3001/vehicleDelete/${CarId} you need to register the route properly at the server.
You should add the catch blocks with Promises, it is recommended practice.
const DeleteVehicles = (CarId) => {
Axios.delete(`http://localhost:3001/vehicleDelete/${CarId}`)
.then((response) => {
if (response) {
console.log(response)
alert("Sikeres Törlés")
navigate("/admin");
}
else {
console.log("törlési hiba")
}
}).catch(console.log);
}

Writing Mocha Chai Test cases for NodeJs Controllers

I am new to unit testing. I am trying to write test cases for controller.js files for nodejs microservices files. I am unable to understand where I am going wrong. Always throws an error "TypeError: Cannot read property 'empId' of undefined" for 2 of these properties.
This is the controller code:
const crmgDetails = db.crmgResource_details;
const employeeProposal = db.employee_Proposal;
const Op = db.Sequelize.Op;
const raDetails = db.crmgRaSheet_entity;
let results = [];
Sequelize = require('sequelize')
exports.findOne = (req, res) => {
console.log(req.body.empId);
crmgDetails.findAll({where: {
resEmployeeNumber: req.body.empId
}
})
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving tutorials."
});
});
};
exports.findMatchingDemandsForRmg = (req,res) => {
let proposedDemands = [];
employeeProposal.findAll({
where: {
emp_id: req.body.empId,
demandSbu : req.body.sbu
}
}).then(proposedEmployee => {
console.log('proposedEmployee',proposedEmployee);
if(proposedEmployee.length === 0){
crmgDetails.findAll({
where: {
resEmployeeNumber: req.body.empId,
demandSbu: req.body.sbu
}
}).then(matchingDemands => {
console.log('matchingDemands ',matchingDemands)
proposedDemands = matchingDemands;
})
}
else{
console.log("crmg Employee")
console.log(proposedEmployee)
for(let employee of proposedEmployee){
crmgDetails.findOne({
where: {
demandUid: employee.demandUid,
resEmployeeNumber: req.body.empId,
demandSbu: req.body.sbu
}
}).then( crmgProposed=> {
proposedDemands.push(crmgProposed);
})
}
}
setTimeout(() => {
console.log(proposedDemands)
res.send(proposedDemands);
}, 3000);
}).catch((err)=>{
res.status(500).send({
message:
err.message || "Some error occurred while retrieving tutorials."
});
})
}
exports.getResourceAllocationDetails = (req,res) => {
employeeProposal.findAll({
include: {
model: raDetails
},
where: Sequelize.and(
{activeFlag : true},
Sequelize.or({status:"Accepted By RMG"},
{status:"Rejected"}
))
}).then(employees => {
res.send(employees)
})
}
This is the test file I tried to write without my head:
const CrmgRaSheetModel = require('../controllers/crmgResource_Details.controller')
describe('Check for succcessful fetech API call', () => {
it('property getResourceAllocationDetails should be called', async () => {
CrmgRaSheetModel.getResourceAllocationDetails((res) => {
expect(res).to.be.an('object')
return res.json()
})
});
it('property findMatchingDemandsForRmg should be called', async () => {
CrmgRaSheetModel.findMatchingDemandsForRmg((res) => {
expect(res).to.be.an('object')
return res.json()
})
});
it('property findOne should be called', async () => {
CrmgRaSheetModel.findOne((res) => {
expect(res).to.be.an('object')
return res.json()
})
})
})
from test file you are calling controller method with only res, so no chance to send your input as your body.
So pass req,res both and pass your input value in req

Simple get request with node.js and express

I have tried everything and can't figure out what i am doing wrong. I have no problem posting data from the client to the server but the other way around i can't get it to work.
The only response i get in my client is ReadableByteStream {}.
This is my code on the client:
export function getAllQuestionnairesAction(){
return (dispatch, getState) => {
dispatch(getAllQuestionnairesRequest());
return fetch(API_ENDPOINT_QUESTIONNAIRE)
.then(res => {
if (res.ok) {
console.log(res.body)
return dispatch(getAllQuestionnairesSuccess(res.body));
} else {
throw new Error("Oops! Something went wrong");
}
})
.catch(ex => {
return dispatch(getAllQuestionnairesFailure());
});
};
}
This is my code on the server:
exports.all = function(req, res) {
var allQuestionnaires = [];
Questionnaire.find({}).exec(function(err, questionnaires) {
if(!err) {
console.log(questionnaires)
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ a: 1 }));
//res.json(questionnaires)
}else {
console.log('Error in first query');
res.status(400).send(err);
}
});
}
I'm doing some guesswork here, since I'm not sure what flavor of fetch you are currently using, but I'll take a stab at it based on the standard implementation of fetch.
The response inside the resolution of fetch typically does not have a directly readable .body. See here for some straight forward examples.
Try this:
export function getAllQuestionnairesAction(){
return (dispatch, getState) => {
dispatch(getAllQuestionnairesRequest());
return fetch(API_ENDPOINT_QUESTIONNAIRE)
.then(res => {
if (res.ok) {
return res.json();
} else {
throw new Error("Oops! Something went wrong");
}
})
.then(json => {
console.log(json); // response body here
return dispatch(getAllQuestionnairesSuccess(json));
})
.catch(ex => {
return dispatch(getAllQuestionnairesFailure());
});
};
}

Resources