为什么我无法使用post方法,错误post not found (404)?我成功连接到数据库,我在 server.js 中定义了路由端点 POST 并在 Signup.vue 中定义了 axios.post 但在 Signup.vue 中返回未找到帖子(404)
//server.js
import express from 'express';
import bodyParser from 'body-parser';
import { MongoClient } from 'mongodb';
import { ServerApiVersion } from 'mongodb';
const app = express();
const port = 5173;
app.use(bodyParser.json());
const uri = "mongodb+srv://22022638:[email protected]/?retryWrites=true&w=majority&appName=MusibDB";
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
});
async function connectToDatabase() {
try {
await client.connect();
console.log("Connected to MongoDB");
} catch (error) {
console.error("Error connecting to MongoDB:", error);
}
}
connectToDatabase();
app.post('/signup', async (req, res) => {
try {
const { username, password, email } = req.body;
const database = client.db("musicApp");
const collection = database.collection("users");
collection.insertOne({ username, password, email });
res.status(200).json({ message: "Đăng ký thành công" });
} catch (error) {
console.error("Đăng ký thất bại:", error);
res.status(500).json({ message: "Đăng ký thất bại" });
}
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
//Signup.vue
async signup() {
try {
await axios.post('/api/signup', {
username: this.username,
password: this.password,
email: this.email,
});
alert('Đăng ký thành công');
this.$router.push('/listfavour');
} catch (error) {
alert('Đăng ký thất bại');
}
}
我通过邮递员检查,但返回 404。我是 StackOverFlow 的新手,请原谅我并帮助我解决问题。非常感谢!
首先,您尝试调用 /api/signup 路由,但您只在后端定义了 /signup post 路由。 其次,如果您之前没有定义baseURL,则不能仅使用axios 调用/api/signup。有关更多详细信息,请参阅文档:https://axios-http.com/docs/config_defaults