Struggling to develop a basic front end that can communicate with my API. The API functions properly as I am able to retrieve and send data using the POSTMAN client. Fetching data from the server and displaying it on the frontend works fine, but encountering difficulties when attempting to post to the API.
Encountering this error message when trying to post the data: script.js:45
POST http://127.0.0.1:5500/users net::ERR_ABORTED 405 (Method Not Allowed)
(anonymous) @ script.js:45
Here is the form I am trying to submit:
<form>
First name: <input type="text" name="firstname" id="firstname"><br>
Last name: <input type="text" name="lastname" id="lastname"><br>
Age: <input type="number" name="age" id="age"><br>
<button type="submit">Send to backend</button>
</form>
The following JavaScript code is embedded in the frontend:
// function updatePost(){
const firstname = document.getElementById('firstname')
const lastname = document.getElementById('lastname')
const age = document.getElementById('age')
const button = document.querySelector('button')
button.addEventListener('click',(e)=>{
e.preventDefault()
var obj = {
firstname: firstname.value,
lastname: lastname.value,
age: age.value
};
fetch('/users',{
method: "POST",
// headers:{
// "content-type":"application/json"
// },
body: JSON.stringify(obj)
})
})
// }
// updatePost()
And here is the post route, which represents the server-side logic:
app.post('/users', async(req, res)=>{
var {firstname, lastname, age} = req.body
console.log(req.body)
let conn;
try {
console.log(firstname, lastname, age)
conn = await pool.getConnection()
const result = await conn.query("insert into info (firstname, lastname, age) VALUES (?, ?, ?)", [firstname, lastname, age])
res.json({
"res": "Your code is working correctly."
})
} catch (error) {
res.send(error)
} finally {
// await poolModule.releaseConn(conn);
conn.release()
}
})
app.listen('3008',()=>{
console.log('Server is up and running')
})
Sensing that there might be something crucial that I am overlooking, any assistance will be highly appreciated. If you require additional information or further codes for troubleshooting purposes, feel free to request them. Thanks.