I'm using react, node, express, postgress. How would I go about using express routes to pass multiple parameters? for example:
This is my route:
//Get entries from materials2 table
app.get("/materials2/:id1&:id2", async (req, res) => {
try {
const {material_thickness, material_width} = req.params;
const contact = await pool.query(
`SELECT *
FROM materials_inventory
WHERE
(material_thickness = $1) AND
(material_width BETWEEN ($2-0.5) AND ($2 0.5))`, [material_thickness, material_width]);
res.json(contact.rows[0]);
} catch (err) {
console.error(err.message);
}
})
The idea is that I need to pass two parameters to the search query
From the react side I have:
const stateSetter = async (thickness, width, length, length2) => {
try {
const response = await fetch(`http://localhost:5000/materials/${thickness, width}`, [thickness, width])
const jsonData = await response.json();
console.log(thickness);
} catch (err) {
console.log(err.message)
}
}
So the idea is that stateSetter receives some values, uses those with the route. How can I go about this? Thanks!
CodePudding user response:
You can use request query
. Change the route in node like so:
//Get entries from materials2 table
app.get("/materials2", async (req, res) => {
try {
const {materialThickness, materialWidth} = req.query;
const contact = await pool.query(
`SELECT *
FROM materials_inventory
WHERE
(material_thickness = $1) AND
(material_width BETWEEN ($2-0.5) AND ($2 0.5))`, [materialThickness, materialWidth]);
res.json(contact.rows[0]);
} catch (err) {
console.error(err.message);
}
})
And you call in the frontend like so:
const stateSetter = async (thickness, width, length, length2) => {
try {
const response = await fetch(`http://localhost:5000/materials2?materialThickness=${thickness}&materialWidth=${width}`)
const jsonData = await response.json();
console.log(thickness);
} catch (err) {
console.log(err.message)
}
}
Also, you were calling the endpoint materials
form you frontend, but specified it as materials2
in node. I updated that in the answer but keep in mind.