i am trying to create a simple front end that can interact with my api. Currently the api is okay I can GET data and POST my data when using POSTMAN client for the requests. So far I can get data from the server and load it into the frontend, but trying to post into the api is where I get the challenge.
this is the error that I get when i try 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
to show you what i have done, 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>
Below is the javascript code contained 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 below is my post route which is 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 denis"
})
} catch (error) {
res.send(error)
}finally {
// await poolModule.releaseConn(conn);
conn.release()
}
}
)
app.listen('3008',()=>{
console.log('server is working')
})
I feel that there is something I am missing, and would appreciate the help. incase more information is needed I can place all my codes here for the error to be reproduced. Thanks.
You're opening your HTML page via the Live Server extension. This is a static web server designed mostly for serving static assets (HTML, CSS, JavaScript, images, etc).
When you attempt to use fetch('/users', { method: 'POST' })
, that POST request is sent to Live Server which cannot handle it. You should instead send the request to your Express service.
To do this, there are two options...
Instead of Live Server, use Express to serve your static content. For example
app.use(express.static('path/to/html/files'));
and open your browser at http://localhost:3008/...
Now any relative or path-only requests like /users
will go to the right place.
or...
Enable CORS in your Express app and make cross-origin requests.
Install the cors
middleware
npm i cors
Enable it
import cors from 'cors'; // or const cors = require('cors')
// ...
// Enable CORS first
app.use(cors({
origin: ['http://localhost:5500'],
}));
// then other request-handling middleware, eg
app.use(express.json());
Make your request to Express
fetch('http://localhost:3008/users', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(obj),
})