Guide on inserting a new user to the db.json

My database file, db.json, has the following structure:

{
  "users": [
    {
      "id": 0,
      "isActive": true,
      "balance": "$2,309.20",
      "picture": "http://placehold.it/128x128",
      "age": 26,
      "accessLevel": "guest",
      "firstName": "Robin",
      "lastName": "Whitaker",
      "company": "REMOTION",
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0c2dfd2d9de9ec7d8d9c4d1dbd5c2f0c2d5dddfc4d9dfde9ed3dfdd">[email protected]</a>",
      "phone": "+7 (845) 419-3899",
      "address": "442 Hanson Place, Tonopah, Washington, 5118",
      "about": "Ut occaecat cillum esse eu Lorem sit dolore. Fugiat cillum occaecat ad consequat ex irure velit ullamco occaecat Lorem fugiat qui consectetur do. Proident sunt eu sint cupidatat quis. Fugiat ad sunt eu sint velit anim eiusmod commodo incididunt excepteur deserunt ex exercitation. Mollit sunt incididunt sint ut et.",
      "registered": "21.03.2016"
    },
    {
      "id": 1,
      "isActive": true,
      "balance": "$2,746.85",
      "picture": "http://placehold.it/128x128",
      "age": 22,
      "accessLevel": "guest",
      "firstName": "Richardson",
      "lastName": "Adkins",
      "company": "OCEANICA",
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7103181219100315021e1f5f10151a181f02311e1214101f1812105f1c14">[email protected]</a>",
      "phone": "+7 (902) 517-3328",
      "address": "117 Beverley Road, Maxville, South Dakota, 6701",
      "about": "Nulla nulla do cillum dolore commodo incididunt laborum labore laboris nisi cillum cillum do. Lorem exercitation nisi proident est adipisicing adipisicing eiusmod labore velit pariatur id enim. Aliquip fugiat adipisicing et dolor eu minim irure anim ea cupidatat. Pariatur magna duis ullamco anim culpa nisi nostrud.",
      "registered": "12.04.2014"
    }
   ]
}

In addition, I have a user form for adding new users:

https://i.sstatic.net/MbMHZ.png

When attempting to add a new user to db.json:

<template>
    <div>
        <h3>Add user</h3>
        <hr>
        <template>
            <user-form-add v-model="user" /> // userForm on the PICTURE!
            <button type="button" class="btn btn-success" @click="save">Save</button>
            <button type="button" class="btn btn-danger" @click="cancel">Cancel</button>
        </template>

    </div>
</template>
<script>
    import axios from '@/axios.js'
    export default {
        name: 'AddUserPage',
        components: {
            UserFormAdd: () => import('@/components/UserFormAdd.vue')
        },
        data:() => ({
            user: {
            },
            restUrl: '/users'
        }),
        computed: {
            id() {
                return null
            },
            url() {
                return `${this.restUrl}/${this.id}`
            }
        },
        methods: {
            redirectToList () {
                this.$router.push('/users')
            },
            save() {
                axios
                    .put(this.url, this.user)
                    .then(() => this.redirectToList())
                    .catch(error => `Error: ${error}`)
            },
            cancel() {
                this.redirectToList()
            }
        }
    }
</script>

However, upon saving, the console returns the error message:

PUT /users/null 404 1.492 ms - 2

By setting the id as:

id() {
    return 0
}

The first object in my db.json is replaced with the new user:

PUT /users/0 200 1.397 ms - 143

I am puzzled by this issue and seek assistance. Thank you.

Answer №1

If you want to register a new user, simply use a POST request. There is no need to include an ID in the request. However, if you wish to modify an existing user profile, you will need to submit a PUT request along with the user's current ID.

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

Utilizing Vue CLI plugin to dynamically pass JS variables as props

I am currently using version 4.5 of the Vue CLI plugin. I have created a component that takes in a title as a prop. This component has been converted into a web component and added to an HTML webpage (which is not a Vue JS project) Now, I am attempting to ...

"Dealing with an unspecified number of fields in an ExtJS data model

I have a data model that is designed to accommodate various incoming data by keeping it generic and allowing for the addition of multiple meta data tags to my project. How can I effectively map these data fields to the Model or access them in the array w ...

Image swaps with timer for button

I am working on a project where I have a page with 5 image buttons arranged horizontally. The objective is to have the images on each button change sequentially every 3 seconds in a continuous loop. Here is my code: $(document).ready(function (){ Beg ...

Adding design to distinct element after clicking a button

Struggling with a JS/Jquery issue on my portfolio website, I admit that I am still just an average programmer. My portfolio website has five buttons, each representing a different project. For each project, there is a corresponding text description and an ...

A step-by-step guide to adding an object to an already existing array in Vue.js

Within the code snippet below, I am dealing with an object value and trying to figure out how to push it to an existing array. methods: { onChange(event) { this.newItems.push(event.target.value); console.log(event.target.value); } } Here is m ...

What could be the reason for my CORS headers not aligning even though they appear to be identical?

I encountered an issue while using passport js with REACT. When trying to fetch the logged in user data, I faced a problem where the cors header of fetch didn't match even though they are identical. Here is the endpoint I am sending the fetch request ...

VueJS Error: Unable to access the 'className' property of an undefined variable

I'm currently working on a menu design project where I need to highlight the active tab/page that the user is on by adding a color class and utilizing JavaScript to update the active link. Here's a snippet of my template: <div class="menu ...

VueJS - repeating input fields for file uploads

I need help removing duplicate items from an array in JavaScript, but when I try to delete one, it always deletes the last occurrence! let app = new Vue({ el: '#app', data: { items: [] }, methods: { addItem() { this.items ...

The initial attempt at using Ajax inside onbeforeunload is unsuccessful

I have attempted to attach the beforeunload event by executing the subsequent script in order to use AJAX to navigate to a specific URL. However, I am encountering an issue where AJAX does not work the first time when I refresh the page, as the URL is no ...

Exploring ways to validate the existence of a class in HTML table elements

If I want to verify if each element has a specific class when creating tables and clicking on the corresponding cells above them, This is what I have tried. However, it did not work as expected. How can I make this work correctly? What am I missing her ...

Navigating nested objects in JSON from an API: A guide to accessing hidden data

I am currently utilizing the cryptocomare API to retrieve data on various crypto coins within a Nextjs App. My approach involves redirecting users to the coin details page when they click on a specific symbol. I then attempt to extract this clicked symbol ...

Selecting radio buttons using Bootstrap and JavaScript

I'm interested in incorporating this bootstrap radio selection feature into my JavaScript code. For example, if option1 is true, I want to execute a specific action... How can I achieve this? <div class="alert alert-info" role="alert"> < ...

After attempting to install @mui/system, I encountered an error. I decided to uninstall it, but now I am consistently facing this

ERROR in ./node_modules/@mui/material/Unstable_Grid2/Grid2.js 6:14-25 export 'createGrid' (imported as 'createGrid2') was not found in '@mui/system/Unstable_Grid' (module has no exports). Encountering an issue after installin ...

Can Googlebot detect changes made to an HTML <title> tag using JavaScript?

Within my website, I have a search engine that operates using ajax technology. My goal is to assign a unique <title> for every search request made. This involves modifying the title each time I receive a response from the ajax feature. I am wonderin ...

Node.js retrieves values through the app.get and app.post methods

In my project, I'm utilizing the app.get and app.post functions in Express on Node.js. Below is an example of how I have used the app.post function: app.post('/status', function(req, res) { if (~packages.STATUSES.indexOf(req.body['s ...

Need to return to the previous page following submission

Is there a way to redirect me to the premontessori page after I submit the form? Below is my function handleSubmit: handleSubmit(event) { event.preventDefault(); <Link to='/premontessori' style={{textDecoration:'none'}} & ...

Transform the API response from a string into an array containing multiple objects

How can I transform a string API response into an array of objects? When making a GET request, the result is returned as a single long string: const state = { strict: true, airports: [] }; const getters = { allAirports: (state) => state.ai ...

JavaScript not displaying properly in Django application deployed on Heroku

Recently deployed a Django application on Heroku, and encountered an issue where the Javascript file hosted on Amazon S3 is not rendering on any page except for the home page. However, upon checking the Console in Inspect Element, it appears that everythin ...

Execute a function and simultaneously input data into MySQL using Node JS

Is there a way to simultaneously insert data from multiple external data sources into a database? I have several APIs/Endpoints that provide the same dataset, and I want to insert them all at once. For instance: Right now, my code loops through each API ...

Tips on how to bring in a module from index.js

Recently, I set up a sample node.js project: "name": "example", "version": "1.0.0", "type": "module", Let's take a look at the index.js (only two lines): "use strict"; import ...