I am trying to make a post API using Node.js using MySQL database, API is giving no response only throwing error - code: 204
I am inserting data using Postman -
{
"articleid":"1233wawdasyyyd4",
"userid": "123uu"
}
In MySQL table there are 4 fields.
id(unique and incrementing) articleid (varchar) userid (varchar) datetime (current timestamp)
var deletelog = (req, res) => {
const articleid = req.body.articleid;
const userid = req.body.userid;
var sql = `INSERT INTO deletearticles_log (articleid, userid)
VALUES ('"+articleid+"', '"+userid+"')`;
connection.query(sql,[articleid, userid], function (error, results, fields) {
if (error) {
res.send({
"code":400,
"failed":"error ocurred",
"error": error
})
}else{
if(results.length >0){
res.send({
"code":200,
result : results
});
}
else{
res.send({
"code":204,
"success":"Record insertion Failed!"
});
}
}
});
}
I don't figured out what's the issue in this code, I appreciate if you could help me, Cheers!!
There are parameters passed for the query [articleid, userid], yet no parameters appear in the SQL. Replace the concatenation in the SQL with question marks.
var sql = `INSERT INTO deletearticles_log (articleid, userid) VALUES (?, ?)`;
Related
I'm writing REST API in node js.
In my database I have two FK (user_A, user_B)
user_A - int (FK)
user_B - int (FK)
create_date - date
My GET request:
http://localhost:3000/chats?useridA=1&useridB=1
And my code:
app.get('/chats/:useridA/:useridB', (req, res) => {
mysqlConnection.query("SELECT * FROM Chats WHERE user_A_app_id = ? AND user_B_app_id = ?",
[req.params.useridA, req.params.useridB], (err, rows) => {
try
{
res.send(rows);
}
catch (err)
{
console.log(err.message);
}
})
});
The output in postman is the entire table and not the specific row.
What's the problem in my code or in my get request?
In general the "WHERE" statement in my code is not working with more then one parameters.
This is the "create table Chats" in my sql file for my database
your GET request is using query parameters:
http://localhost:3000/chats?useridA=1&useridB=1
So to use it inside your nodejs code, you can access those parameters us:
req.query.useridA
req.query.useridB
So the request should be like this:
app.get('/chats/:useridA/:useridB', (req, res) => {
mysqlConnection.query('SELECT * FROM Chats WHERE user_A_app_id =' +req.param("useridA")+ 'AND user_B_app_id =' +req.param("useridB")', (err, rows) => {
try {
res.send(rows);
}
catch (err) {
console.log(err.message);
}
})
});
or you just call get request using url parameters
http://localhost:3000/chats/:useridA/:useridB
http://localhost:3000/chats/1/1
I am trying to send users to two different pages based on whether an SQL query is successful or not on an express backend. But only the success route is showing when I use this code.
I previously did not have the await statement in, but had the same issue. I'm not sure whether the react side is taking in the error message as a response, as it's still logging into the console from the backend.
Here is the method in the frontend which is called when the form is submitted:
e.preventDefault();
console.log(this.state);
const newPost = {
pet_name : this.state.pet_name,
content : this.state.content,
content : this.state.content,
owner : 'testOwner',
email : 'test#gmail.com',
img_path : this.state.upload_image
};
//fetch instead of this to talk about in diss
try {
const postData = await axios.post('http://localhost:3306/reportpet', newPost)
.then(res=>console.log(res.data));
this.props.history.push('/postsubmitted')
} catch(error) {
console.log("Catch = ", error.response);
this.props.history.push('/posterror')
}```
The route on the backend is as follows:
```router.post('/reportpet', function (req, res) {
var pet_name = req.body.pet_name,
content = req.body.content,
date = req.body.date,
owner = req.body.owner,
email = req.body.email,
img_path = req.body.img_path;
const query = "INSERT INTO `posts` (`post_id`, `pet_name`, `content`, `date`, `owner`, `email`, `img_path`) VALUES (?, ?, ?, UTC_TIMESTAMP(),?, ?, ?);"
console.log(query);
connection.query(query, [pet_name, pet_name, content, owner, email, img_path ], function(err, result) {
(err)?res.send(err+'error was created'):res.json(result);
if (err) throw err;
console.log('rows inserted')
})
})
module.exports = router
When the data is not added to the database, I expect the user to be sent to the error component. When it is successful, I expect the success component to display.
Try to skip using .then() in await.
And be sure that your backend returns the response with proper HTTP error code (4xx or 5xx) so the axios knows that error happened.
try {
const postData = await axios.post('http://localhost:3306/reportpet', newPost)
console.log(postData);
this.props.history.push('/postsubmitted')
} catch(error) {
console.log("Catch = ", error.response);
this.props.history.push('/posterror')
}
Mykola Prymak answered this. I had a response sending the error instead of throwing it, removing that and adding the response underneath the throw fixed it.
Code in the backend is now this:
const query = "INSERT INTO `posts` (`post_id`, `pet_name`, `content`, `date`, `owner`, `email`, `img_path`) VALUES (null, ?, ?, UTC_TIMESTAMP(),?, ?, ?);"
console.log(query);
connection.query(query, [pet_name, content, owner, email, img_path ], function(err, result) {
// (err)?res.send(err+'error was created'):res.json(result); {removed code}
if (err) throw err;
res.json(result);
console.log('rows inserted')
})
```
I'm building a server and i'm trying to know if a key is in my sql DB.
I want to know if it is possible to get only the value of sql request or do I need to parse it?
function checkKey(key) {
var sqlcheck = "SELECT customerID from authentification where discord_key =
?";
console.log("in function");
DB.query(sqlcheck, [key], function (err, result) {
if (err) throw err;
console.log(result);
});
}
this is what I get :
RowDataPacket { customerID: 'cus_ET5gXP7p7Tafmf' }
but I am looking to get only:
cus_ET5gXP7p7Tafmf
Thank you for your help!
generally
result[0].customerID
however in your example it looks like
result.customerID
First of all, I have to tell you I'm pretty noob in this "universe". I'm using: ExpressJs, MySql, Body-Parser, Express-session, Ejs template for creating an Basic Contacts Application in Node.
My database is composed from 3 tables:
user (user_id, first, second name, username, password)
contacts (ct_id, first, second name, phone numb.)
user_contacts (user_id, ct_id) --> foreign keys for user and contacts
I want to listing on /myProfile page all details about user and his contacts.
I don't know how to handle the select queries.
So, after some documentation I did this:
conn.query('SELECT * FROM user_contacts WHERE user_id= ?', req.session.user_id, function (err, result) {
if(err) throw err;
console.log(result);
var queryArray = "";
for(var i = 0; i < result.length; i++){
queryArray += `SELECT * FROM contacts WHERE ct_id= ${result[i].ct_id}; `;
}
console.log(queryArray);
conn.query(queryArray, function (err, result) {
if(err) throw err;
console.log(result);
res.render('myProfile/contacts', {
title: `${req.session.user_nickname}'s Contacts`,
data: result
});
});
});
But I have an error
ER_PARSE_ERROR: You have an error in your SQL syntax;
..when queryArray.length > 1
I searched and it's something about Multiple statement queries but I dont know how to solve it.
Edit 2:
I modify my code..
conn.query('SELECT * FROM user_contacts WHERE user_id= ?', req.session.user_id, function (err, result) {
if(err) throw err;
var datas = [];
for(var i = 0; i < result.length; i++){
getContacts = function(query){
conn.query(query, function (err, result) {
console.log('Creating data');
data = {
user: req.session.user_nickname,
contact:{
ct_firstName: result[0].ct_firstName,
ct_SecondName: result[0].ct_SecondName,
ct_PhoneNumber: result[0].ct_PhoneNumber
}
}
return data;
});
}
console.log('Send data to array');
datas.push(getContacts(`SELECT * FROM contacts WHERE ct_id = ${result[i].ct_id}`));
}
console.log(datas); // [ undefined, undefined ]
res.render('myProfile/contacts',{
title: `${req.session.user_nickname}'s profile`,
data: datas
})
});
But now my array contain undefined objects?? Any solution?
Maybe is something about scope?
My result:
Send data to array
Send data to array
[ undefined, undefined ]
Creating data
Creating data
I push the object to array before creating it. How is it possible?
1797,
I noticed you have several small queries grabbing the contact info for a given user. You could simplify your code by combining your queries into a single one. Often times 1 big query is more efficient (plus it's easier to maintain). I'm using a join. More info here.
const contacts = [];
const query = "
SELECT c.*
FROM user_contact uc
JOIN contact c ON uc.contact_id = c.contact_id
WHERE uc.user_id = ?
GROUP BY c.contact_id
";
conn.query(query, req.session.user_id, (err, results) => {
if (err) throw new Error(err);
// it seems that this could just be 'contacts = results' since they
// have the same structure
contacts = results.map(result => {
return {
ct_firstName: result[0].ct_firstName,
ct_SecondName: result[0].ct_SecondName,
ct_PhoneNumber: result[0].ct_PhoneNumber
};
});
res.render('myProfile/contacts',{
title: `${req.session.user_nickname}'s profile`,
data: contacts
});
});
I've come across a situation where I need to use a bulk insert with my Node project.
This of course has already been answered here: How do I do a bulk insert in mySQL using node.js
However, I have an express project which I use to create an api. The parameters are turned into an array and I'm having trouble using that array with a bulk insert. Whenever I try to use that route, I get an error of Error: ER_WRONG_VALUE_COUNT_ON_ROW: Column count doesn't match value count at row 1
After some digging I found that it tries to insert:
['foo', 'bar', 'test']
When I need it to insert:
['foo']
['bar']
['test']
Anyways, here's the whole code:
Route
router.post("/", function (req, res, next) {
db.query(
"REPLACE INTO user (`Name`) VALUES (?)",
[req.query.array],
function (error, response) {
if (error) throw error;
console.log(response);
}
)
});
Route Caller
let requestUrl = "http://localhost:3000/user?";
// External api request which returns a list of users
for (let i = 0; i < body.users.length; i++) {
requestUrl += `array=${body.users[i]}&`
}
let addUserRequest = {
url: requestUrl,
method: "POST"
};
request(addUserRequest, function (error, response, body) {
console.log(body);
});
The url that is generated is:
http://localhost:3000/user?array=foo&array=bar&array=test
Try this,
var datatoDB = [];
req.query.array.forEach(function(entry) {
console.log(entry);
datatoDB.push([entry]);
});
Here we are trying to convert this ['foo', 'bar', 'test'] to this [["foo"], ["bar"], ["test"]].
Now, use datatoDB in your function.
router.post("/", function (req, res, next) {
db.query(
"REPLACE INTO user (Name) VALUES ?",
[datatoDB],
function (error, response) {
if (error) throw error;
console.log(response);
}
)
});