我试图通过 fetch 向我的服务器发送一些数据,尽管我收到了 404 错误 项目使用的是vite+react
前端:
async function submitBtn () {
var data={
password:Password,
login:Login
}
alert('Login: ' + Login + ' Password: ' + Password)
const jsonData = JSON.stringify(data);
const body = JSON.stringify({
jsonData
})
const config = {
"headers":{
"Content-Type":"application/json"
}
}
try{
const response = await axios.post('http://localhost:5173/api/data', body, config)
console.log(response)
} catch(error){
console.log(error)
}
}
后端:
const express = require("express");
const app = express();
const port = 5173;
app.use(express.json()); // Enable JSON parsing
app.get('/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}`);
});
我很确定我的服务器正在运行,但它根本没有帮助。
在您的后端代码中,您没有处理该特定路径的 POST 请求。您必须使用
app.post
来处理 POST 请求,在您的代码中,您使用 app.get
来处理 GET 请求。
后端:
app.post('/api/data', (req, res) => { // Change get to post
console.log(req.body); // Log the received data
res.status(200).json({ message: 'Data received successfully' });
});