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

Jest fails to pass when encountering the double colon

Having issues testing a React app using Jest. I encounter errors when running my code: FAIL src\App.test.js ● Test suite failed to run C:/Users/user1/Projects/map-editor/src/App.js: Unexpected token (40:33) 38 | <div cla ...

PHP MySQL - Automatically trigger email notification upon insertion of a new record

Is there a way to trigger an email alert only when a new record is added, not when the user edits input fields in a table? The database I'm working with stores equipment delivery dates. Users schedule deliveries and input the dates into a SQL Server ...

The animation came to a halt after a brief period

Here is the code I wrote. When the button is clicked, the 3 containers should start flashing indefinitely, but they stop after a while. I can't figure out why. Any ideas? <!DOCTYPE html> <html> <head> <title></title> & ...

When using TypeScript with custom components as children in React, the `type` returned by React.Children is a string representing the function

It might sound a bit odd, or maybe I'm completely off track here. While going through some articles and React documentation on getting children and identifying specific child components using React.Component.map(), I ran into an issue with my custom c ...

Personalized AngularJS required text

After utilizing the built-in AngularJS directive required and encountering a validation error, I receive a small popup near the field displaying "Please fill out this field". My issue lies in needing the text to be displayed in another language. How should ...

I am facing an issue with Lotties having a black background in my NextJS project. Is there a way to make them transparent

I am facing an issue with my LottieFiles (JSON) displaying a black background when imported into my NextJS project. Despite trying to set background='transparent' on both the Player and parent div, the problem persists. I made sure to export my ...

Using Dynamic Parameters in NodeJS Route Definitions

I am currently working with a route that has the following structure: app.route('/api/*/*/*') .get(function(req, res){ var entitya = req.params['0']; var entityb = req.params['1']; var entity3 = req.params[' ...

What could be causing my function to output unicode replacement characters instead?

As I work on enhancing password security by implementing encryption, my goal is to store the hashes and perform encryption/decryption during signup/login processes. The encryption process works smoothly, converting from utf8 to hex without any issues. Howe ...

Ways to set up various Content-Security-Policies and headers in your application?

In my email application, I am trying to prevent alerts in JavaScript by using a CSP header. However, even with the current policy in place, alerts can still execute when I send an HTML document attachment that contains script tags. Changing all JavaScript ...

Tips for customizing your MUI slider design

import * as React from "react"; import Box from "@mui/material/Box"; import Slider from "@mui/material/Slider"; function valuetext(value) { return `${value}°C`; } export default function RangeSlider() { const [value, se ...

Is the reference to a variable within an array maintained by JavaScript?

I'm working with react code and using the find() method to select an item from an array. When I retrieve an item from the array, is JavaScript copying the item or returning a reference? EDIT: The items in my array are objects, such as [{id: 12, name ...

The fadeOut() function is not functioning properly as the div keeps reappearing even after attempting to

My navigation bar has a unique feature - the subnav expands to fullscreen on hover, while all other subnavs close. However, I encountered an issue with the close button functionality. When clicked, the subnav fades out but then immediately fades back in. ...

Flexbox helps create responsive layouts with ease

Utilizing flex to centrally position my element within my layers has worked well for me, but I encountered an issue when switching to a smaller screen size. The element simply scales down in size instead of taking up the full width like it does with Bootst ...

Tips for displaying dynamic content in VueJS?

I'm currently working on an app that allows users to choose which type of vuetify element they want to display on the page. There are 4 options available for selection. My goal is to render the corresponding vuetify component when a user clicks on the ...

Can you explain the concept of BuildOptions in Sequelize?

Despite poring through the sequelize documentation and conducting extensive searches online, I have yet to come across a satisfactory answer: Why is BuildOptions necessary and what impact does it have on the created model? import { Sequelize, Model, Data ...

Retrieve the dynamically generated element ID produced by a for loop and refresh the corresponding div

I am facing a challenge with my HTML page where I generate div IDs using a for loop. I want to be able to reload a specific div based on its generated ID without having to refresh the entire page. Here is a snippet of my HTML code: {% for list in metrics ...

Displaying various pop-up notifications upon clicking a table element

I am completely new to VueJS and I'm currently working on populating a table with various columns, one of which contains a button that triggers the opening of a modal. There are three different types of modals that can be opened based on certain condi ...

Sending AJAX data from VIEW to CONTROLLER in PHP (MVC) using AJAX: A step-by-step guide

I have a page at http://visiting/blog. The Controller contains two methods: action_index and add_index. When Action_index() executes, it returns pages with indexes. On the other hand, Add_index() invokes a model's method called add_data(), which inse ...

Using Axios to Integrate an API - Displaying a Username and Password Pop-up

I have been given a project that involves API integration. I have successfully retrieved data from the API, but there is a pop-up appearing asking for a username and password. Although I have these credentials, I would like to log in without that pop-up ap ...

Error in Adding Items to React To-Do List

As I work on creating a React todo app following a tutorial, I have encountered an issue. Despite having components and context files set up, the addItem function does not render the item and date into the todo list when the 'Add todo' button is ...