我正在尝试向我的服务器发送 POST 请求,但收到 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)
}
}
后端(ExpressJS):
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}`);
});
我很确定我的服务器正在运行,但它根本不起作用
HTTP 404 错误代码,又名“找不到页面”错误表示服务器无法在给定的 URL 或路径中找到请求的内容。
在您的后端,您仅使用
app.get("/api/data", ...)
处理“/api/data”的 GET 请求。服务器无法找到处理“/api/data”处的 POST 请求的方法,因此您还需要使用 app.post("/api/data", ...)
。
在你的情况下,我相信你只想处理“/ api / data”的POST请求,所以后端代码将是这样的:
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' });
});