I can't insert data to my database (mysql) - javascript

I'm learning now MySQL and I have a some problem. I tried to make a post request to my db::
My code from client side:
async function sendValues() {
const settings = {
method: 'post',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(product)
}
try {
const fetchResponse = await fetch('http://localhost:9001/products', settings);
const data = await fetchResponse.json();
console.log(data) // what the user send
} catch (err) {
return err
}
}
My code from server side:
router.post('/', (req, res) => {
const { c_id, p_name, p_price } = req.body
const q =
`
INSERT INTO products (c_id,p_name,p_price)
VALUES("${c_id}", "${p_name}" , "${p_price}")
`;
con.query(q, (err, result, fields) => {
if (err) throw err;
res.json(result)
});
});

There are two possible mistakes:
1.check the connection between client and server. as mentioned above.
2.check the table name, data type of attributes, name of attributes you are providing.

The rest endpoint is / and you are calling products change your backend code as below.
router.post('/products', (req, res) => {
const { c_id, p_name, p_price } = req.body
const q =
`
INSERT INTO products (c_id,p_name,p_price)
VALUES("${c_id}", "${p_name}" , "${p_price}")
`;
con.query(q, (err, result, fields) => {
if (err) throw err;
res.json(result)
});
});

Related

How to use sql returning id in front-end JavaScript?

I have this request in server.js file.
app.post("/insertRowtoMain", (req, res) => {
const {nodeid, maintenancetype, personnel, process, date} = req.body;
//console.log("description",description)
let insertQuery = `insert into maintenance(nodeid,maintenancetype, personnel, process, date)
values(${nodeid},'${maintenancetype}',${personnel},'${process}', '${date}') returning id`
pool.query(insertQuery, (err, result) => {
if (!err) {
console.log("insertRowtoMain", result.rows);
res.status(200).send(result.rows);
} else {
res.status(404).json(err.message)
console.log("insertRowtoMain error", err.message)
}
})
})
And I am calling this request function in front-end with this code:
const addNewMainTypes = async () => {
try {
await axios.post(`${serverBaseUrl}/insertRowtoMain`, {
nodeid: newMaintenance.nodeid,
maintenancetype: newMaintenance.maintenancetype,
personnel: newMaintenance.personnel,
process: newMaintenance.process,
date: newMaintenance.date,
});
} catch (err) {
throw err;
}
const maintenance = await getMain();
// console.log("main list", maintenanceList);
setMaintenance(maintenance);
const maintenanceList = await getMainTypes();
// console.log("main list", maintenanceList);
setMaintenanceList(maintenanceList);
};
When I insert a new row to this function, I got the returning id in server.js terminal.
How can I use that Id in front-end?
Save the response of the POST request in a variable and access the data property
// Here, "data" will be a variable with the response data
const { data } = await axios.post(`${serverBaseUrl}/insertRowtoMain`, {
nodeid: newMaintenance.nodeid,
maintenancetype: newMaintenance.maintenancetype,
personnel: newMaintenance.personnel,
process: newMaintenance.process,
date: newMaintenance.date,
});
/* Seems like your API is returning an array of objects with "id" property, so, for example... */
// The following should console.log the first element's id of the array
console.log(data[0]?.id);

How to get a variable from Frontend to the Backend using get API in reactjs with Express API

I want to get information from my freight Shipment table in order to process other information I need to do in the frontend. But I don't know how to grab the email of the logged-in user using Axios.get() method to use it to query my MySQL DB.
in my frontend, I defined a useState of loggedEmail and I am setting it to the currently logged-in user. how can I pass that to my backend using the GET method?
here is my code:
server:
app.get('/api/freightID', (req, res) => {
const email = req.body. //how would i get the email from the front end to use it in my query?
db.query("SELECT * FROM freight_shipment WHERE user_email = ?", email, (err, result) => {
if(err){
console.log(err)
}
if(result.length > 0 ){
res.send(result);
}
});
});
Frontend:
const [loggedEmail,setLoggedEmail] = useState("");
Axios.defaults.withCredentials = true;
useEffect(() => {
Axios.get('http://localhost:3001/login').then((response) => {
if(response.data.loggedIn == true){
setLoggedEmail(response.data.user[0].email)
setLoginStatus(response.data.loggedIn);
console.log(response.data.loggedIn)
}
})
},[]);
useEffect(() => {
Axios.get("http://localhost:3001/api/freightID").then((response) => {
console.log(response);
})
});
There is a config object in Axios.get where you can put your params there to send them to BE
You would use it like so:
Axios.get("http://localhost:3001/api/freightID", {
params: { email: loggedEmail }, //<-- Put params here
}).then((response) => {
console.log(response);
});
Then in your BE, you would get it like so:
app.get('/api/freightID', (req, res) => {
const email = req.query.email //<-- It's here in the req.query
db.query("SELECT * FROM freight_shipment WHERE user_email = ?", email, (err, result) => {
if(err){
console.log(err)
}
if(result.length > 0 ){
res.send(result);
}
});
});
You can pass the loggedEmailin Get as a query param or path param.
Please take a look at this article. https://masteringjs.io/tutorials/axios/get-query-params.
In your case you can do like:
const params = {
loggedInUserEmail: loggedEmailin
};
Axios.get(`http://localhost:3001/api/freightID/{params.loggedInUserEmail}`)
and in Server side you can get value
app.get('/api/freightID/:email', (req, res) => {}) etc ... ///
var end = req.params['email']

Knex, inserting random columns

What I am trying to do is use knex's trx in order to post data to my database. When I try to send a post request and process it with the following code I get this error:
Failing row contains (4, null, , null, 2021-05-13 23:12:17.642)
I don't have much experience with knex so I have no clue why there are two null values in with the three values that are supposed to be there. I feel like this is simple but I can't find anything on it online.
const handleAnnouncementCreation = (req, res, db) => {
const { body } = req.body;
db.transaction(trx => {
trx.insert({
body: body,
posted: new Date()
}).into('news_posts').returning('id').then(id => {
res.json(id);
}).then(trx.commit).catch(trx.rollback);
}).catch(err => res.status(400).json(err));
}
The issue is that you are trying to assign a Json value (the value of body) into a column.
You should use JSON.stringify on the body value.
const handleAnnouncementCreation = (req, res, db) => {
const { body } = req.body;
db.transaction((trx) => {
trx
.insert({
body: JSON.stringify(body), // <--
posted: new Date(),
})
.into('news_posts')
.returning('id')
.then((id) => {
res.json(id);
})
.then(trx.commit)
.catch(trx.rollback);
}).catch((err) => res.status(400).json(err));
};

Unable to fetch data from MySQL database with Fetch API

I'm able to post successfully to MySQL database with Fetch API. The problem I'm having is trying to retrieve data from my database.
client.js:
const output = document.getElementById('output');
const username = document.querySelector('#username');
const date = document.querySelector('#date');
const submitbtn = document.querySelector('#submitbtn');
const commentOutput = document.querySelector('#message');
const form = document.querySelector('#form');
const comments = document.getElementById('message')
form.addEventListener('submit', function(e) {
e.preventDefault(e);
sendMessage();
let formMessage = new FormData(form);
formMessage.append('api-key', 'myApiKey');
fetch('http://localhost:5502/superhero', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({ comments: comments.value })
}).then(function(response) {
console.log(response)
console.log(JSON.stringify({ comments: comments.value }))
return response.json()
}).then(function(data) {
console.log(data);
}).catch(function(error) {
console.log(error);
});
})
submitbtn.addEventListener('click', function() {
fetch('http://localhost:5502')
.then(response => {
if (response.ok) {
console.log('success')
} else {
console.log('failure')
}
return response.json();
})
.then(data =>
console.log(data))
.catch(error => console.log('Error'))
var newUser = document.createElement("div");
var newName = document.createElement("h5");
var newDate = document.createElement("h5");
var newMessage = document.createElement("h6");
newName.textContent = comments.value;
newDate.textContent = message.value;
newMessage.textContent = message.value;
output.appendChild(newName);
output.appendChild(newDate);
output.appendChild(newMessage);
output.appendChild(newUser);
})
The problem here is the fetch method under the submitbtn:
Output:
index.js:
router.post("/superhero", function(req, res) {
const user = req.user;
const comments = req.body.comments;
sqlDatabase.query("INSERT INTO comments (user_id, comments) VALUES (?, ?)", [user, comments],
function(error, results, fields) {
console.log(results);
console.log(comments);
console.log('This is: ', comments)
console.log(error)
if (error) throw error;
});
})
router.get("/superhero", authenticationMiddleware(), function(req, res, err) {
sqlDatabase.query("SELECT users.username, comments.comments, comments.date FROM users INNER JOIN comments ON users.user_id=comments.user_id",
function(error, results, fields) {
if (error) throw error;
console.log(results);
console.log(error);
res.render('superhero');
})
})
I want to retrieve that data under router.get
Hope this is enough details. Thanks in advance. Noob by the way.
The res.send actually send back the JSON response
router.get("/superhero", authenticationMiddleware(), function(req, res, err) {
sqlDatabase.query("SELECT users.username, comments.comments, comments.date FROM users INNER JOIN comments ON users.user_id=comments.user_id",
function(error, results, fields) {
if (error) throw error;
console.log(results);
console.log(error);
res.send({heros: results}); //<-- send back the JSON response
})
})
Also, you can add condition if you're rendering on the server side as well
if (req.accepts('json')) {
res.send({hero: 'superhero'}); // <-- try sending back JSON object but rather a string
// OR
res.send({heros: results});
else {
res.render('superhero');
}
If you're using Express then you can use response.json method as well.
Finally got the results I wanted. I just created another api for retrieving data from my server file and changed
this:
fetch('http://localhost:5502/superhero')
to:
fetch('http://localhost:5502' + '/get_messages')
app.get("/get_messages", function(request, result) {
sqlDatabase.query("SELECT users.username, comments.comments, comments.date FROM users INNER JOIN comments ON users.user_id=comments.user_id",
function(error, results) {
result.end(JSON.stringify(results));
console.log(results);
});
});
So I have a route for rendering a view, and one for retrieving the data

Passing a variable from ReactJS frontend to NodeJS back end using a GET route

I am working on a react app and am trying to find a way to pass a variable I define in my front-end (Question.js) to my back-end (server.js) so that I can issue different queries. I have the code
//Question.js
state = {
data: null
};
componentDidMount() {
this.callBackendAPI()
.then(res => this.setState({ data: res.express }))
.catch(err => console.log(err));
}
callBackendAPI = async () => {
const response = await fetch('/express_backend');
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message)
}
return body;
};
//server.js
con.connect(function (err) {
if (err) throw err;
con.query("SELECT question FROM s1questions WHERE ID = 1", function (err, result, fields) {
if (err) throw err;
app.get('/express_backend', (req, res) => {
var x = JSON.stringify(result[0].question);
res.send({ express: `${x}` });
});
});
});
Your sever should probably split your database connection from your route handler definitions. Also, you could use query parameters to access questions based on their id in the database.
// question.js
callBackendAPI = async () => {
const response = await fetch(`/express_backend?questionId=1`);
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message)
}
return body;
};
// server.js
app.get('/express_backend', (req, res) => {
const { questionId } = req.query;
// query database for question by id
});

Categories

Resources