I would like to explain my problem of the day.
I have an error 500 I cannot find where it comes from.
How can I fix this issue?
my fonction:
handleSubmit = (e) => {
e.preventDefault();
const userIdData = { id : e.target.id};
const config = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userIdData),
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
if (res.error) {
alert(res.error);
} else {
alert(`ajouté avec l'ID ${res}!`);
}
}).catch(e => {
console.error(e);
}).finally(() => this.setState({ redirect: true }));}
routes :
app.delete('/api/alluserpls', (req, res, ) => {
const userId = req.body.id;
const formData = req.body
connection.query('DELETE alluserpls WHERE id = ?',[formData, userId], err => {
if (err) {
res.status(500).send("Erreur lors de la modification des users");
} else {
res.sendStatus(200);
}
});
});
can you try this
app.delete('/api/alluserpls', (req, res, ) => {
const userId = req.body.id;
const formData = req.body
connection.query('DELETE * from alluserpls WHERE id = ?',[ userId], err => {
if (err) {
res.status(500).send("Erreur lors de la modification des users");
} else {
res.sendStatus(200);
}
});
});
as you only need to pass the id of the user to delete it
you have an issue in your database query. Your DELETE query is wrong. It should be
DELETE * from table_name where condition;
connection.query('DELETE * from alluserpls WHERE id = ?',[userId], err => {
if (err) {
res.status(500).send("Erreur lors de la modification des users");
} else {
res.sendStatus(200);
}
});
Related
I am curious if it is possible to use a fieldname as a parameter for express.
My sql statement is as follows:
const INSERT_VALUE_VIA_FIELD = "UPDATE businesses set ? = ? where userId = ?";
...
router.post("/update", async (req, res) => {
const { field, value, userId } = req.body;
connection.query(
INSERT_VALUE_VIA_FIELD,
[field, value, userId],
async (error, rows) => {
res.set("Access-Control-Allow-Origin", "*");
if (error) {
res.json({ error: error.sqlMessage });
req.on("end", () => {
res.statusCode = 400;
res.end("Bad Request");
});
} else {
res.json({ field, value, userId });
req.on("end", () => {
res.statusCode = 200;
res.end("OK post");
});
}
}
);
});
I pass in the properties as follows:
{
"field": "name",
"value":"test",
"userId": 23
}
in which i expect the mysql statement to run as:
"UPDATE businesses set name = "test" where userId = 23";
When i run this via postman, i get the following error:
"error": "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '('name') = 'test' where userId = 23' at line 1"
Any ideas?
So it isnt the most feasible answer, but it works. I have substituted the string with back ticks as suggested by Mostafa and passing in the field param within the statement as so:
router.post("/update", async (req, res) => {
const { field, value, userId } = req.body;
connection.query(
`UPDATE businesses set ${field} = ? where userId = ?`,
[value, userId],
async (error, rows) => {
res.set("Access-Control-Allow-Origin", "*");
if (error) {
res.json({ error: error.sqlMessage });
req.on("end", () => {
res.statusCode = 400;
res.end("Bad Request");
});
} else {
res.json({ field, value, userId });
req.on("end", () => {
res.statusCode = 200;
res.end("OK post");
});
}
}
);
});
I am trying to upload an image file using mutler along with some form data. Every solution I've looked suggests to disable the bodyparser but if I disable the body parser then I cannot parse the request body.
Backend POST api along with function that runs middleware:
case 'POST':
if (req.body instanceof FormData) {
await runMiddleware(req, res, upload.single('image'))
}
console.log('ID: ',req.query.id)
Courses.findByIdAndUpdate(req.query.id, req.body, {new: true}, (err, result) => {
if(err)
{
console.log('Error in findByIdAndUpdate: ',err)
res.status(400).json({ success: false, data: result })
}
else {
console.log('Success in findByIdAndUpdate: ',result)
res.status(200).json({ success: true, data: result })
}
})
below is the function
function runMiddleware(req, res, fn) {
return new Promise((resolve, reject) => {
fn(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
Upload Middleware
import multer from "multer";
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "public/uploads");
},
filename: (req, file, cb) => {
cb(null, "upload" + Date.now() + "-" + file.originalname)
}
})
module.exports = multer({storage})
Front-End API call
const createUpdateFormData = () => {
const data = {
title: getValues('title'),
categories: getValues('categories'),
description: getValues('description'),
image: (getValues('file') ? getValues('file')[0] : null),
}
let formData;
if (data.image) {
formData = new FormData();
Object.entries(data).forEach(([key, value]) => {
if(value)
formData.append(key, value);
});
}else {
formData = {}
Object.entries(data).forEach(([key, value]) => {
if(value)
formData[key] = value;
});
}
return formData
}
const handleUpdateRequest = (id,formData) => {
console.log(formData)
const updateReq = axios.post(`/api/courses/${id}`, formData)
toast.promise(updateReq, {
loading: "Processing...",
error: (err) => {
console.log(err)
if (err.response.status === 409)
return 'Course already exists!'
else
return 'Oops something went wrong!'
},
success: (res) => {
console.log(res)
const newState = courseState.map(course => course._id === id ? res.data.data : course)
setCourses(newState)
// console.log('NewState: ', courseState)
return "Course updated successfully!"
}
});
}
I am using the useForm hook
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
here is the url in browser
http://localhost:8888/update/1
this is the code for the route
router.addRoute("/update/:id", (req, res) => {
conn.query(
"select * from mahasiswa where ? ",
{ no_induk: req.params.id },
function (err, rows, field) {
if (rows.length) {
if (req.method.toUpperCase() == "POST") {
} else {
let html = view.compileFile("./tamplate/form_update.html")();
res.writeHead(200, { "Contact-Type": "text/html" });
res.end(html);
}
} else {
let html = view.compileFile("./tamplate/form_update.html")();
res.writeHead(200, { "Contact-Type": "text/html" });
res.end(html);
}
}
);
});
please help me i have no idea
I think it's better to use router.post
For example:
router.post("/update/:id", (req, res) => {
conn.query(
"select * from mahasiswa where ? ",
{ no_induk: req.params.id },
function (err, rows, field) {
if (rows.length) {
let html = view.compileFile("./tamplate/form_update.html")();
res.writeHead(200, { "Contact-Type": "text/html" });
res.end(html);
}
}
});
I need some help. It's my first try with promises.
Here is my code for the promise:
const deleteUniversRefInTarget = (universName, targetName) => {
console.log('Appel de deleteUniversRefInTarget')
const promis = new Promise((resolve, reject) => {
Target.findOneAndUpdate({ univers: universName, name: targetName },
(err, target) => {
console.log('Entrée dans la promesse')
if (err) {
reject(err)
} else {
if (target === null) {
reject(TypeError(`Invalid univers'n name ${universName}`))
} else {
if (target.univers.length === 1) {
resolve('deleteTarget')
} else {
target.univers.splice(target.univers.indexOf(universName), 1)
resolve('dereferencedUnivers')
}
}
}
})
})
return promis
}
I call this promise here :
exports.deleteATarget = (req, res) => {
deleteUniversRefInTarget(req.params.universName, req.params.targetName)
.then((response) => {
console.log('Fin du traitement de la promesse')
if (response === 'deleteTarget') {
Target.findOneAndDelete({ name: req.params.targetName, univers: req.params.universName },
(err, target) => {
if (err) {
res.send(err)
}
res.json({ message: `Target ${target.name} isn't used in any univers, so we deleted it` })
})
} else {
res.json({ message: `Target ${req.params.targetName} no longer used in ${req.params.universName} univers` })
}
})
.catch((error) => {
res.send(error)
})
}
In the console, I can see :
Appel de deleteUniversRefInTarget
But not Fin du traitement de la promesse
So ... do you know what I'm doing bad ?
I'm not sure I understood everything, but here is my new code about this anti-pattern :
```
const deleteTargetOrDerefUniversInTarget = (universName, targetName) => {
const promis = new Promise((resolve, reject) => {
Target.findOne({ name: targetName, univers: universName })
.then((target) => {
if (target === null) {
reject(TypeError(`Invalid univers'n name ${universName} or target's name ${targetName}`))
} else if (target.univers.length === 1) {
resolve({ action: 'deleteTarget', target })
} else {
resolve({ action: 'dereferencedUnivers', target })
}
})
.catch((err) => {
reject(err)
})
})
return promis
}
exports.deleteATarget = (req, res) => {
deleteTargetOrDerefUniversInTarget(req.params.universName, req.params.targetName)
.then((response) => {
if (response.action === 'deleteTarget') {
Target.findOneAndDelete({ name: response.target.name, univers: req.params.universName })
.then((target) => {
res.json({ message: `Target ${target.name} isn't used in any univers, so we deleted it` })
})
.catch((err) => {
res.status(err.status).json(err)
})
} else {
response.target.univers.splice(response.target.univers.indexOf(req.params.universName), 1)
response.target.save()
res.json({ message: `Target ${response.target.name} no longer used in ${req.params.universName} univers` })
}
})
.catch((error) => {
res.send(error)
})
}
```
In this new code, no more exec call.
The first promise just send back an action to perform that the caller manage.
Ok, sounds much better when I transform my mongoose query (findOneAndUpdate) to a promise :
`
const deleteUniversRefInTarget = (universName, targetName) => {
console.log('Appel de deleteUniversRefInTarget')
const promis = new Promise((resolve, reject) => {
Target.findOneAndUpdate({ univers: universName, name: targetName })
.exec()
.then((target) =>{
console.log('Entrée dans la promesse')
if (target === null) {
reject(TypeError(`Invalid univers'n name ${universName}`))
} else {
if (target.univers.length === 1) {
resolve('deleteTarget')
} else {
target.univers.splice(target.univers.indexOf(universName), 1)
resolve('dereferencedUnivers')
}
}
})
.catch((err) => {
reject(err)
})
})
return promis
}
`
And the difference is mainly the .exec() part.
I think we can say it's solve ... even if I'm not sure it's the correct way to do ot.