Knex, inserting random columns - javascript

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));
};

Related

How do I import object data in an array in order using axios?

Currently, I can only recall certain arrays. I put the 'length' of the data in '[], but only the last data comes out. (I know why)
How do I sequentially import data from the first object to the last object in an array?
p.s DB: mySQL
Axios code to load data from the first array
const getList = async () => {
axios.defaults.withCredentials = true;
const config = {
headers: {
withCredentials: true,
},
};
try {
//Successful response
const response = await axios.get("url", config);
const data = response.data;
console.log(data);
const id = data[0].BOARD_ID;
const title = data[0].BOARD_TITLE;
const register = data[0].REGISTER_ID;
const date = moment(data[0].REGISTER_DATE).format(
"YYYY MM DD, H:mm:ss a"
);
setBbsData([
{
...bbsData,
id: id,
title: title,
register: register,
date: date,
},
]);
} catch (error) {
//Failed to respond
console.log(error);
}
server code
app.use(cors({ credentials: true, origin: true }));
// api
app.get("url", (req, res) => {
const sqlQuery = "SELECT *FROM BOARD;";
db.query(sqlQuery, (err, result) => {
res.send(result);
});
});
app.listen(PORT, () => {
console.log(`running on port ${PORT}`);
});
Arrays have a map method which allows you to operate on all its elements.
setBbsData(
data.map((item) => ({
id: item.BOARD_ID,
title: item.BOARD_TITLE,
register: item.REGISTER_ID,
date: moment(item.REGISTER_DATE).format("YYYY MM DD, H:mm:ss a"),
})),
);
Here we're taking each item and mapping them to a new object. The parentheses around the brackets are required or else it will be interpreted as a function body and not an object.

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']

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

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)
});
});

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