Reputation: 303
I'm learning how to make rest requests, but got this problem
I have 3 routs
one for insert
app.get("/addUser",(req, res)=>{
let post = {usersName : "user3", userStarus:"1", GroupId : "3"};
let sql = "insert into test.usersnames set ?";
let query = connection.query(sql, post, (err, result)=>{
if(err) throw err;
console.log(result);
res.send("post added");
})
});
ans it works
but 2 others like delete and update doesn't work
app.get("/deleteUser/:id",(req, res)=>{
let sql = `delete from test.usersnames
where usernames.id=${req.params.id}`;
let query = connection.query(sql, post, (err, result)=>{
if(err) throw err;
console.log(result);
res.send("post deleted");
})
});
it returns an error
ReferenceError: post is not defined
what's the difference? why can it insert but can't delete or update a record when i'm trying to pass record's id ?
Upvotes: 0
Views: 2268
Reputation: 8351
In the second query you should use "Escaping query value" something similar to prepared statement to avoid sql injection attacks:
let sql = 'delete from test.usersnames
where usernames.id=?';
connection.query(sql, [ req.params.id ], (err, result) => { ... });
Upvotes: 1
Reputation: 11
When you define a variable with let or const. It's available only in his scope. So in your second request, post isn't define
Upvotes: 1
Reputation: 3166
In first example you are defining the variable post
let post = {usersName : "user3", userStarus:"1", GroupId : "3"};
but not in second one.
Upvotes: 1