When i try to send data to my backend with fetch, it throws out an error 404
it means not found but i cant find how to fix it
Frontend:
const submitBtn = () => {
var data={
password:Password,
login:Login
}
alert('Login: ' + Login + ' Password: ' + Password)
const jsonData = JSON.stringify(data);
fetch('http://localhost:5173/В',{
method:"POST",
headers:{
"Content-Type":"application/json"
},
body: jsonData
})
.then(response => {
if (response.ok){
return response.json()
}else {
throw new Error('Network response was not ok')
}
})
.then(responseData => {
console.log('Servers response: ' + responseData)
})
.catch( error => {
console.error('Error:', error)
})
Backend:
const express = require('express')
const mysql = require('mysql')
const app = express();
const port = 5173;
app.use(express.json());
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*'); // Allow all domains (for development)
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
})
app.post('http://localhost:5173/api/data', (req, res) => {
console.log(req.body); // Log the received data
res.status(200).json({ message: 'Data received successfully' });
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
thanks for help.
i already tried writing different code for both frontend and backend, doesnt seem to work though
2
Answers
The
app.post()
method in your backend file is defining the URL that your frontend can hit.Currently, your frontend is trying to hit
/B
URL, but your backend is only listening onapi/data
.There are a couple of ways you can fix this, but as long as the URL route is consistent between the front and back end, it should work.
For example, you could try:
Frontend
to
Backend
to
The issue seems to be with the way you’re defining the route in your Express backend. Instead of specifying the full URL in
app.post
, you should define just the endpoint. Let’s fix that and make sure the route matches the one you’re trying to access from the frontend.Frontend:
Backend:
In the backend, we’re using
app.post('/api/data', ...)
to define the endpoint for handling the POST request from the frontend. In the frontend, we’re sending the POST request to'http://localhost:5173/api/data'
. Make sure these match, and it should work without a 404 error.