Why I can't use post method, error post not found (404)? I connected successful to database, I defined route endpoint POST in server.js and defined axios.post in Signup.vue but return post not found (404) in Signup.vue
//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');
}
}
I checked by postman but return 404. I'm new to StackOverFlow, please forgive me and help me solve the issue. Thank you so much!