I am trying to send data from FE to BE. I use Vite Here is my code for FE part:
import {useState} from "react";
import axios from 'axios'
import "./search-page/index.css"
function SearchPage(){
const [post, setPost] = useState({
genre: '',
year: ''
});
const handleInput = (event)=> {
setPost({...post, [event.target.name] : event.target.value});
};
function handleSubmit(event){
event.preventDefault();
console.log(post, typeof post);
axios.post("http://localhost:5173/submit-data", {post})
.then(response => console.log(response))
.catch(error => console.log(error));
}
return (
<form onSubmit={handleSubmit} action="/submit-data">
<label htmlFor="genre">Genre: </label>
<input type="text" id="genre" name="genre" placeholder="Enter genre" onChange={handleInput}/>
<label htmlFor="year">Year: </label>
<input type="text" id="year" name="year" placeholder="Enter year" onChange={handleInput}/>
<button type = "submit">Search</button>
</form>
)
}
export default SearchPage;
And here is my BE code:
import express from "express";
const app = express()
app.use(express.json());
const port = 5174
app.listen(port, ()=>console.log(`Listening to port ${port}`))
app.post('/submit-data', async (req, res) =>{
const genre = req.body.genre;
const year = req.body.year;
res.json({message: `Genre ${genre} and year: ${year}`})
})
But i get this error:
code: “ERR_BAD_REQUEST”
config: Object { timeout: 0, xsrfCookieName: “XSRF-TOKEN”, xsrfHeaderName: “X-XSRF-TOKEN”, … }
message: “Request failed with status code 404”
name: “AxiosError”
request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
response: Object { data: “”, status: 404, statusText: “Not Found”, … }
Can anybody point me in the right direction?
I have tried to change the ports, URLs addresses, but nothing changed. I also tried to send a call through Postman with this body:
{
“genre”: “action”,
“year”:
}
but got an 404 error
Sergio is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.