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);
}
Related
I have the following axis post request
EXAMPLE 1
Front End
let data = this.itemsDuplicated;
console.log("length",data.length)
await axios({
method: "post",
url: `${url}/upDateTasksFromProgress`,
data: data
})
.then(response => {
console.log(response.data);
})
.catch(e => {
console.log(e);
});
Node
router.post("/upDateTasksFromProgress", (req, res) => {
let mysql = "";
req.body.forEach(el => {
mysql = `${mysql} update tasks set startDate = '${el.startDate}', endDate = '${el.endDate}', duration = ${el.duration} where id = ${el.id};`
});
console.log(mysql)
pool.getConnection(function (err, connection) {
if (err) {
connection.release();
resizeBy.send("Error with connection");
}
connection.query(mysql, function (error, result) {
if (error) {
console.log(error);
} else {
console.log(result)
res.json(result);
}
});
connection.release();
});
});
This works fine.
I also have:
EXAMPLE 2
Front End
let data = [];
this.tasks.forEach(el => {
let insert = {
id: el.id,
startDate: el.startDate,
endDate: el.endDate,
duration: el.duration,
parentId: el.parentId,
dependantOn: el.dependantOn,
fix: el.fix
};
data.push(insert);
});
console.log(data.length)
await axios({
method: "post",
url: `${url}/postTaskUpdates`,
data: data
})
.then(response => {
console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
Back End
router.post("/postTaskUpdates", (req, res) => {
let mysql = "";
req.body.forEach(el => {
mysql = `${mysql} update tasks set startDate = '${el.startDate}', endDate = '${el.endDate}', duration = ${el.duration}, parentId = '${el.parentId}', dependantOn = '${el.dependantOn}' where id = ${el.id};`
});
pool.getConnection(function (err, connection) {
if (err) {
connection.release();
resizeBy.send("Error with connection");
}
connection.query(mysql, function (error, result) {
if (error) {
console.log(error);
res.json(error)
} else {
console.log(result)
res.json(result);
}
});
connection.release();
});
});
The second example gives me the following error:
“Access to XMLHttpRequest at
'https://www.testing-be.co.za/postTaskUpdates' from origin
'https://www.testing-fe.co.za' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource.”
Both are in the exact same Route File on the backend.
The only difference is the number of records.
In the first example there are 22 records.
In the second there are about 1300 records.
Besides the number of records, all else is as shown above and to my mind exactly the same.
Any suggestions would be greatly appreciated.
I am trying to push the fetched data in an array using foreach but it only returns the first data in the loop. Here is my code.
exports.getAllTrial = async function (req, res, next) {
try {
new Promise( async (resolve, reject) => {
var reservations = [];
await Schedule.getSchedule()
.then(data => {
data.forEach(async (element) => {
await saveReserve.getAllTrial({where: {scheduleID: element.id, date: "8/18/2020"}})
.then(trial => {
trial.forEach(response => {
reservations.push(response.scheduleID)
})
})
console.log(reservations);
resolve(reservations);
})
});
})
.then(value=>{
res.status(200).json(value);
})
.catch(err => {
console.log(err);
});
} catch (e) {
return res.status(400).json({ status: 400, message: e.message });
}
}
My expected output should be: [ 9, 10, 10 ] But it only returns [9].
Async code in a foreach loop is a bad idea, as it won't be executed one after the other. I suggest reading a bit more async/await and the concept of promise, as you are mixing things here (such as mixing await and .then). Also worth looking into Promise.all which will resolve a list of promises and array.map.
While I have no idea of what some variables such as saveReserve are supposed to be or do, your code might be simplified into:
exports.getAllTrial = async (req, res, next) => {
try {
const data = await Schedule.getSchedule()
const reservations = await Promise.all(
data.map(element => {
return saveReserve.getAllTrial({ where: { scheduleID: element.id, date: '8/18/2020' } })
})
)
return res.status(200).json(reservations)
} catch (e) {
return res.status(400).json({ status: 400, message: e.message })
}
}
I am trying to replace a string in url . Here is image of it
in this image I want to replace lssplalpha with lssplprod which are in pics array. For that I created an api . Here is a code
apiRoutes.get('/SchoolListing_lssplalpha_Replace',function(req, res) { schoolListModel.find({},function(err,check){
if(err){
return console.log(err);
}
else{
for(var i=0;i<check.length;){
var f=0;
for(var j=0;j<check[i].pics.length;j++){
f++;
var newTitle = check[i].pics[j].replace("lssplalpha","lsslprod");
check[i].pics[j] = newTitle;
console.log("after change",check[i].pics[j]);
check[i].save(function (err) {
if(err) {
console.error('ERROR!');
}
});
}
if(j==check[i].pics.length&&j==f){
i++;
}
}
console.log("i value",i);
console.log("check length",check.length);
if(i==check.length){
return res.json({status:true,message:"Updated Schools"}); }
}
});
});
I am getting success response . When I go and check database nothing changed in db. To know the reason I write log of it. When I see logs it was replacing correctly. But I didn't understand why those are not reflecting in database? Here is an image of log in console
Please help me to come out of this
The issue here is you are running a for loop (synchronous) where you are calling the model.save() operation which is asynchronous and the loop keeps iterating but the results of the async calls come later. The process of saving a database item in an array takes some time and Node.js knows this, so it starts the update and then just moves on trying to update the next item in the array. Once the write operation is complete a callback function is run, but by that point the loop has completed and there is no way to know which items finish in what order.
You could use the Bulk Write API to update your models. This allows you to sends multiple write operations to the MongoDB server in one command. This is faster than sending multiple independent operations (like) if you use create()) because with bulkWrite() there is only one round trip to MongoDB.
The following examples show how you can use the bulkWrite.
Using async/await:
apiRoutes.get('/SchoolListing_lssplalpha_Replace', async (req, res) => {
try {
let ops = [];
const docs = await schoolListModel.find({}).lean().exec();
docs.forEach(doc => {
const pics = doc.pics.map(pic => pic.replace("lssplalpha", "lsslprod"));
ops.push({
"updateOne": {
"filter": { "_id": doc._id },
"update": {
"$set": { pics }
}
}
});
});
const result = await schoolListModel.bulkWrite(ops);
console.log('Bulk update complete.', result);
res.status(200).json({
status: true,
message: "Updated Schools"
});
} catch (err) {
res.status(400).send({
status: false,
message: err
});
}
});
Using Promise API:
const bulkUpdate = (Model, query) => (
new Promise((resolve, reject) => {
let ops = [];
Model.find(query).lean().exec((err, docs) => {
if (err) return reject(err);
docs.forEach(doc => {
const pics = doc.pics.map(pic => (
pic.replace("lssplalpha", "lsslprod")
));
ops.push({
"updateOne": {
"filter": { "_id": doc._id },
"update": {
"$set": { pics }
}
}
});
if (ops.length === 500) {
Model.bulkWrite(ops).then((err, result) => {
if (err) return reject(err);
ops = [];
resolve(result);
});
}
});
if (ops.length > 0) {
Model.bulkWrite(ops).then((err, result) => {
if (err) return reject(err);
resolve(result);
});
}
});
})
);
apiRoutes.get('/SchoolListing_lssplalpha_Replace', (req, res) => {
bulkUpdate(schoolListModel, {}).then(result => {
console.log('Bulk update complete.', result);
res.status(200).json({
status: true,
message: "Updated Schools"
});
}).catch(err => {
res.status(400).send({
status: false,
message: err
});
});
});
You are running asynchronous call model.save() in for loop(synchronous)
To make your for loop synchronous you can use for...of loop which works asynchronous, also you will not need to add multiple checks like you have done in your code.
Try following code, it will work
apiRoutes.get('/SchoolListing_lssplalpha_Replace', function (req, res) {
schoolListModel.find({},function (err, check) {
if (err) {
return console.log(err);
}
else {
for (let checkObj of check) {
let newPicArr=[];
for (let pic of checkObj.pics) {
pic = pic.replace("lssplalpha", "lsslprod");
newPicArr.push(pic);
}
checkObj.pics=newPicArr;
checkObj.save(function (err) {
if (err) {
console.error('ERROR!');
}
});
}
return res.json({ status: true, message: "Updated Schools" });
}
});
});
I am getting an error that seems to suggest I'm not returning some of my statements, but I think I'm doing everything correctly. Here's the warning:
Warning: a promise was created in a handler at /src/api/podcasts.js:51:18 but was not returned from it
This is the code of the function in question:
'findPodcastById': (db, podcastId, callback) => {
var queryString = "SELECT * FROM podcasts WHERE id=$1;";
db.one(queryString, [podcastId])
.then((result) => {
return callback(null, result);
})
.catch((err) => {
return callback(err, null);
});
},
And the parent function that it's called from:
app.post('/getepisodes', (req, res, next) => {
var podcastId = req.body.podcastId;
var userId = req.body.userId;
var podcast;
podcasts.findPodcastByIdAsync(db, podcastId)
.then((result) => {
podcast = result;
return request(podcast.rss);
})
.then((result) => {
return podcastParser.parseAsync(result, {})
})
.then((result) => {
return Promise.resolve(result.channel.items);
})
.map((item) => {
var date = new Date(item.pubDate).toLocaleString();
return podcasts.addEpisodeAsync(db, podcast.id, item.title, item.enclosure.url.split('?')[0], striptags(item.description), date, item.duration);
})
.map((episode) => {
return posts.addPostAsync(db, 'podcast', episode.id, episode.title, episode.description);
})
.then(() => {
return podcasts.findEpisodesByPodcastIdAsync(db, podcastId, userId);
})
.then((result) => {
return res.json(result);
})
.catch((err) => {
next(err);
});
});
I have a return statement in each promise block, so I'm not sure what I'm doing wrong, I would really appreciate some help!
findPostCastBy id is not returning the promise, try this
'findPodcastById': (db, podcastId) => {
return db.one("SELECT * FROM podcasts WHERE id=$1;", [podcastId])
}
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());
});
};
}