I am a beginner in working with Vue and I'm currently facing an issue while trying to submit user input data to my MongoDB using axios. Although the data from the database is displayed on the page, I can't seem to get the form input data to successfully post. There are no error messages being shown either; it simply isn't posting the data. I eagerly await your response and guidance on where I might be going wrong. Below is the code snippet for my AddUser.vue page on the client-side:
<template>
<div>
<h1>Registration</h1>
<p>First name: </p>
<b-form-input v-model="firstname">
</b-form-input>
<p>Last name: </p>
<b-form-input v-model="lastname">
</b-form-input>
<p>Email: </p>
<b-form-input v-model="email">
</b-form-input>
<p>Password: </p>
<b-form-input v-model="password">
</b-form-input>
<br>
<button v-on:click="submitNew">Submit</button>
</div>
</template>
<script>
import UserService from "../UserService";
export default {
name: "UserEdit",
data(){
return {
editUsers: this.$route.query.user,
editStatus: "",
user: {}
}
},
methods: {
submitNew(){
try{
this.user = UserService.addUsers;
} catch (err) {
this.error = err.message;
}
this.cancel();
}
},
watch :{
$route: "updateRouter"
}
}
</script>
Shown below is the UserService.vue file on the client-side:
import axios from "axios";
const mongoURL = "http://localhost:5000/api/posts";
class UserService{
static getUsers(){
return new Promise(async (resolve,reject)=> {
try{
const res = await axios.get(mongoURL);
const users = res.data;
resolve(
users.map((users) =>({
...users,
}))
);
} catch (err) {
reject (err);
}
});
}
static addUsers(user){
return axios.post(mongoURL, {
user
})
}
export default UserService;
Here's a snippet of the Users.js model file on the server-side:
const mongoose = require('mongoose');
const User = mongoose.model("User",{
firstname: {
type: String,
required: true,
trim: true
},
lastname: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
trim: true
},
password: {
type: String,
required: true
}
})
module.exports = User;
Lastly, here is the posts.js file from the server-side:
const express = require("express"),
mongoose = require("mongoose"),
User = require("../models/Users.js"),
router = express.Router();
router.get("/", async (req,res)=>{
try {
const user = await User.find({});
res.send(user);
} catch (error){
res.status(500).send(error);
}
});
router.post("/", async(req,res)=>{
console.log(req.body["user"]);
const user = new User(req.body["user"])
console.log(user);
try{
await user.save
console.log(user)
} catch(err){
res.status(550).send(err);
}
})
module.exports = router;