I need to know how to create a patch request in Vue.js and simultaneously modify the marks input for specific individuals by using v-model

Hello there, I am currently developing a student assessment input form using vuejs, express, and mongoDB. The backend API is complete and functioning properly when tested with postman. Here is the code:

// UPDATE MARKS
router.patch('/:studentId', async (req, res) => {
    try{
    const updatedStudent = await Assessment.updateMany({_id: req.params.studentId},
        {
            $push:
            { homework: req.body.homework,
              classtest:req.body.classtest, 
              projectwork:req.body.projectwork, 
              exams:req.body.exams },
        });
        res.json(updatedStudent);
            }catch (err) {
                res.json({ message: err });
    }
});

I am facing challenges integrating it with the vuejs frontend. I have created a JavaScript file 'assessment.js' to handle all requests as shown below;

import axios from 'axios';

const url = 'http://localhost:9000/contAssessment/';
   ...
    // Add Marks
    static addMarks(homework) {
        return axios.patch(url, {
            homework
        });
    }
}

export default assessmentService;

I have imported it into the marks component form like this;

<template>
    <div id="container">
        <div 
            v-for="assessment in assessments" 
            v-bind:key="assessment._id"
            >
            <div id="students_marks_info"
            v-if="assessment.students.classes===classes"
            > 
            <p> {{assessment.students.name}} </p> 
            <p> <input type="text" v-model="homework"> </p>
            </div>
        </div>
        <button type="submit" v-on:click="addMarks(homework)">Submit</button>
    </div>
</template>


<script>
import assessmentService from '../assessmentService';

export default {
  name: 'marksEntryForm',
  data() {
    return {
      assessments: [],
      error: '',
      classes: '',
      homework: []
    }
  },
  async created() {
    try {
      this.assessments = await assessmentService.getAssessments();
    } catch(err) {
      this.error = err.message;
    }
  },
  methods: {
   async addMarks() {
      await assessmentService.addMarks(this.homework);
      this.assessments = await assessmentService.getAssessments();
      }
    }}
</script>

Whenever I click the submit button to run the addMarks method, I receive a 404 bad request. Additionally, I am encountering issues with the input field where marks entered for one student appear in other students' inputs. As a newcomer to vuejs and axios for patch requests, I would greatly appreciate your guidance on resolving these issues. Thank you.

Answer №1

The server provides the router at here_is_your_url/:studentId, but the request from the front end is redirected to

http://localhost:9000/contAssessment/
(which does not include a :studentId)

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

Next.js encountered an issue when trying to read properties of null, specifically the 'push' property, resulting in a TypeError

I am utilizing the sweetalert2 library for displaying popups: export default function Home() { const MySwal = withReactContent(Swal) useEffect(() => { MySwal.fire({ showConfirmButton: false, customClass: { ...

Using three.js to input text instead of particles within a particle cloud

I have a unique three.js codepen project where square particles drift through the space. However, I am now looking to enhance it by incorporating text (perhaps using geometry?) instead of the square particles, creating a word/tag cloud effect. Is this eve ...

Can I modify individual properties of xAxis.labels in HighCharts?

I am seeking to customize the properties of my labels on the x-axis in a unique way (View my query here). I have a clear understanding of how to achieve this for dataLabels: See API reference. This process is akin to what has been explained here. Howeve ...

AngularJS: Index not refreshing after deletion of array item(s) using their indexes

I am attempting to eliminate a specific item from an array variable within AngularJS's scope by using the item's index. If you believe this question is a duplicate, please check out the footnote links for related questions that were not exactly ...

Leverage Jasmine for testing a jQuery plugin

I'm currently utilizing the angular-minicolors library () within an angular controller: angular.element("myelement").minicolors({ position: 'top left', change: function() { //custom code to run upon color change } }) Wh ...

What is the best way to deploy a REST API utilizing an imported array of JavaScript objects?

I have been using the instructions from this helpful article to deploy a Node REST API on AWS, but I've encountered a problem. In my serverless.yml file, I have set up the configuration for the AWS REST API and DynamoDB table. plugins: - serverless ...

Navigating a plethora of unpredictable identifiers using AngularJS

My goal is to display content from a json file that varies in type and consists of pages divided into chapters. Users can navigate through the content using an aside menu or next and previous buttons. Currently, I am able to display the content by inserti ...

Storing data in MongoDB upon the emission of a Socket.io event

In my project, I am using a MEAN stack and Socket.io to retrieve images from the real-time Instagram API. The current setup is functioning well, but now I want to store image data in a MongoDB database to maintain a record of images based on locations, rat ...

What is the process of sending a post request using axios to insert data into a database in React

I am currently working on a login system using mysql, axios, express, and react. The database connections are functioning properly, but I am encountering errors specifically with these two posts, displaying messages like "ERR_CONNECTION_REFUSED" and UNCAUG ...

Can an ID and a "<?php echo ''.$variable.'' ?>" be included in the same input or video tag?

I have a task where I need to insert various Ids into a single video input tag. Specifically, I need to include the player and its row ids from PHP in this format: <video preload controls playsinline id="player[<?php echo ''.$row5['id ...

What is the process for declaring a member variable as an extended type in TypeScript?

Is it possible to declare a "member variable" as an "extension object" rather than a static type (without relying on an interface)? Imagine something like this pseudocode: class Foo { bar -> extends Rectangle; constructor(barInstance:IRec ...

What is the best way to capture videos using Safari?

Hey there! I've set up the browser camera on my website for users to record live tests. It's been working great on Chrome and Firefox using MediaRecorder, but unfortunately, Safari isn't cooperating. Does anyone know of an alternative to Me ...

ES6/JS: Locate a specific text within a nested object and return a true value

I need help filtering a vuetify data-table. You can find the codepen link here: https://codepen.io/rasenkantenstein/pen/MWYEvzK. I have a filter with the string "Ice", and I want to retrieve all records that contain an ingredient with "ice" in its name. [ ...

The process of displaying only the month name as the title in Full Calendar

Is there a way to display the Full Calendar title with only the month name instead of "month name year name"? Here is my code attempt: $('#calendar').fullCalendar({ header: { left: 'prev', center: 'title' ...

Slick.js integrated with 3D flip is automatically flipping after the initial rotation

I'm encountering an issue with my CSS3 carousel and 3D flipping. Whenever I navigate through the carousel and flip to the next slide, the first slide seems to automatically flip/flop after completing the rotation. You can see a visual demonstration o ...

Getting Started with NextJs and Firestore Setup

Recently, I have been incorporating Firebase into my NextJs project. I've set up a file called initFirebase.tsx for the server-side implementation. import * as Sentry from '@sentry/nextjs'; import * as admin from 'firebase-admin'; ...

Guide on passing the set[State] function to a trigger component that is not a descendent

Take a look at this diagram. ChildComponentB contains a state called stateX. In ChildComponentA, when a certain event occurs, it should modify the stateX in ChildComponentB. If ChildComponentA is a child component of ChildComponentB, passing the setStateX ...

What is the best way to transfer data from one worker to all the others in node.js?

Upon node boot up, I initialize an in-memory JavaScript object. This node app runs on multiple cores using the cluster module. When an HTTP request is received, it is handled by one of the worker threads which then modifies the value of the JavaScript ob ...

Curved Edges Ensure Non-Interactive Elements

element, there is a query about utilizing a color wheel from a repository on GitHub. The goal is to disable any actions when clicking outside of the canvas border radius in this color wheel. Various steps need to be taken to prevent unwanted outcomes: - S ...

Tips for postponing the first button event in Vue 3 and JavaScript

My current task involves setting up a button event in Vue 3 that triggers a setTimeout countdown on the button before redirecting to another page. The event function has a conditional statement that initiates a countdown from 5 to 0 as long as the countVal ...