Having trouble saving user input from a form to a database using axios, mongodb, and vue?

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;

Answer №1

<template>
    <div>

        <h1>Sign Up</h1>

        <p>First Name: </p>

        <b-form-input v-model="user.firstname">

        </b-form-input>

        <p>Last Name: </p>

        <b-form-input v-model="user.lastname">

        </b-form-input>

        <p>Email Address: </p>

        <b-form-input v-model="user.email">

        </b-form-input>

        <p>Password: </p>

        <b-form-input v-model="user.password">

        </b-form-input>

        <br>

        <button v-on:click="submitNew">Submit</button>

    </div>
</template>

<script>
import AuthService from "../AuthService";

export default {
    name: "UserSignup",
    data() {
        return {
            signupUsers: this.$route.query.user,
            signupStatus: "",
            user: {}
        }
    },
    methods: {
        submitNew() {
            try {
                this.user = AuthService.register(this.user);
            } catch (err) {
                this.error = err.message;
            }
            this.cancel();
        }
    },
    watch: {
        $route: "updateRouter"
    }
}
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for changing one tag into a different tag?

Can someone help me with this issue? I need to change the tags in a given string from <h2> to <h3>. For example, turning <h2>Test</h2><p>test</p> into <h3>Test</h3><p>test</p>. Any suggestions o ...

switch the anchor tag value and send it along with the URL

I am trying to update the value of "trans" in the Ajax URL based on a toggle between on and off values. However, despite successfully toggling the text, the URL parameter does not change accordingly. Can anyone offer any assistance? I currently have to rel ...

Searching for the latest messages while categorizing them by two specific fields using Mongoose

I am looking to create a contact list based on the most recent messages exchanged with a contact. In order to achieve this, I need to sort the last messages (both sent and received), combine them, and then retrieve the most recent one. Here is the expecte ...

combine elements from a different document using a local field as a key

I'm currently working on a project involving a competition document with a field teams array of objects containing the _id of each team, as well as a score document with a teamId field. The competitions.teams array looks like this: [{_id: 100,..}, {.. ...

Searching and selecting columns in React using Material-UI

Currently, I am using Material-UI data tables and have implemented a search functionality similar to this Codesandbox example, which only searches the Name/Food column. This is my existing code snippet: const [filterFn, setFilterFn] = useState({ fn: items ...

Can a Firestore Realtime Query be reutilized after being in the background in order to cut down on expenses?

In my Vue PWA, I am utilizing the firebase-js-sdk to receive realtime updates from Firestore. When bringing the app back from being in the background, I rely on "vuex-persist" to maintain the app state. In addition to the app state, it is necessary for me ...

Remove the array element if the value is blank

I have an array with different objects, and I need to efficiently delete the entries where the name is empty, similar to the first and third object in the example below: var myArray = [ { "Name": "", "Value": "" }, { "Name": "aaa", "Value": "bbb" ...

Issue Alert: Error encountered while rendering: "TypeError: route is not defined"

Greetings! Would you mind identifying the specific error for me? ...

How should one go about creating an npm package out of a vuejs component and testing it locally?

Initially, I created a vuejs project as a test container using vue-cli. Next, I developed an npm package named "vue-npm-example" from a Vuejs component in my local environment and then imported it into the aforementioned testing project. Within the packag ...

Is there a way to improve error readability in React when using webpack?

Attempting to solve the issue, I decided to make a change in my npm script. Initially, it was set to operate in production mode by default: The original script looked like this: "client": "webpack -w --config ./gen/config/webpack.config.js& ...

Building a personalized version with core-js

I am currently in the process of developing a custom build using core-js. Following the instructions provided, I initiated the following commands: npm i core-js && cd node_modules/core-js && npm i The process seemed to go smoothly. Then, ...

Tips for effectively making REST requests from a ReactJS + Redux application?

I'm currently working on a project using ReactJS and Redux, incorporating Express and Webpack as well. I have successfully set up an API and now need to figure out how to perform CRUD operations (GET, POST, PUT, DELETE) from the client-side. Could so ...

Angular JS Tutorial: How to Nest ng-views

When merging two separate Angular apps into one, I encountered the need to nest ng-views. The structure of my sample code (index.html) looks like this: <!doctype html> <html lang="en" ng-app="myApp"> <head> <meta ch ...

Attempting to iterate through and retrieve the names listed in the table

I have a code that I need help with in extracting names from td elements using jQuery. In certain instances, if the td is empty, I want to merge the left-side td with the 5 right-side tds because the first td on the right side is empty and the second td c ...

NodeJS Async: Having trouble grasping the sequence of events

async.each( driver, function(apiRequest, cb) { apicall(apiRequest, cb); }, function(err) { console.log("error..."); } ); function apicall(item, cb) { request( 'https://api.mlab.com/api/1/databases/db/co ...

Tips for optimizing performance by preloading external CSS and JavaScript files from a third-party source in a ReactJS project with webpack

Is there a method similar to using ProvidePlugin for preloading jQuery that can be used to preload third-party CSS and JS files without using import in the entry JS file? The reason I am interested in preloading these files is because I encountered an err ...

React Router Redux causing an infinite loop when navigating back

I recently encountered a strange issue with my React + Redux app. I am using React Router in combination with React Router Redux for routing, and I noticed some unexpected behavior. Clicking the back button once takes me from route 0 to -1 successfully. Ho ...

Merge JSON objects into an array

Is there a way to merge JSON objects when the initial object is: { "total": "2" } And the second one is: [ "player1": { "score": "100", "ping": "50" }, "player2": { "score": "100", "ping": "50" ...

The caret operator in NPM does not automatically install the latest minor version of a package

Within my package.json file, one of the dependencies listed is labeled as... "@packageXXX": "^0.7.0", Upon running the "npm outdated" command, I observed that... @packageXXX current: 0.7.0 wanted: 0.7.0 latest: 0.8.0 Despite executing "npm ...

"An error occurred with the Google chart due to 'null' not being recognized as an object, specifically in relation to the select menu and onchange event

Currently, I have implemented the following Script: <header> <script type="text/javascript" src="http://www.google.com/jsapi"></script> </header> <body> <script type="text/javascript"> google.load("visualization", "1 ...