Im creating a crud web app for university using nodejs express mysql. I’ve created an api that will allow me to get data from my database, which seems to be working fine. But when handling POST requests, all I am getting is undefined input and returned to the database whenever I am on the main.js, using a form to handle this on an ejs page. I’ve checked the POST in postman and this method seems to work fine so im not sure where im going wrong.
Main.js
router.post('/add', (req, res) => {
let name = req.query.name; // Access query parameter
const insertData = {
nameField: name
};
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
let endpoint = "http://localhost:4000/pokemon/add";
// Move the Axios POST request inside the callback function of res.send()
axios.post(endpoint, insertData, config)
.then((response) => {
let insertedid = response.data.respObj.id;
let resmessage = response.data.respObj.message;
res.send(`${resmessage}. INSERTED DB id ${insertedid}`);
})
.catch((err) => {
console.log(err.message);
// Handle errors
res.status(500).send('Internal Server Error');
});
});
router.get('/add', (req, res)=> {
res.render('add');
});
App.js api
app.post('/pokemon/add',(req, res)=> {
let Pokename = req.body.nameField;
let addPoke = `INSERT INTO card (name)
VALUES ('${Pokename}')`;
connection.query(addPoke, (err,data) => {
if(err) {
res.json({err});
throw err;
}
if(data){
let respObj ={
id: data.insertId,
name: Pokename,
message: `${Pokename} pokemon added to cards`,
};
res.json({respObj});
}
});
});
add.ejs
<form method="POST" action="/add">
<label>
<input name="name" type="text" placeholder="Title">
</label>
<button type="submit">Submit</button>
</form>
<button class='button success'>add</a>
</form>
</div>
Tried changing my routes and variable names, double checked everything matches but I could be wrong.
Any help is appreciated. Thanks