Encountering an issue when attempting to update by pressing the button

I am encountering a challenge in my Vue application that involves inserting, updating, and deleting posts using MongoDB. Specifically, I am facing an issue with the update function. Whenever I attempt to update a post by clicking the corresponding button, I receive the following error message. It should be noted that in the postComponent.vue file, I recently included a template showcasing how the form is submitted, as well as the function within the script tag updatePost.

The error reads: Access to fetch at 'http://localhost:5000/api/posts/5e31a39024a21d44bc4654af' from origin 'http://localhost:8080' has been blocked by CORS policy: Method UPDATE is not allowed by Access-Control-Allow-Methods in preflight response.

posts.js

//update posts
router.put('/:id', async (req,res) => {
    const posts = await loadpostscollection();

    await  posts.updateOne({
        topic: req.body.topic,
        price: req.body.price,
        location: req.body.location,
        provider: req.body. provider,
        createdAt: new Date()
    });
    res.status(201).send();
});

postServise.js

//update Posts
    static updatePost( id, topic, price, location, provider) {
        return fetch(url + id, {
            method: "UPDATE",
            mode: 'cors',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=UTF-8'
            },
            body: JSON.stringify({
                    topic,
                    price,
                    location,
                    provider
                }
            )
        });
    }

postComponent.vue

<template>
<div class ="container">
    <router-link to="/postComponent" >Show me post component</router-link>
  <h1>Create a new course</h1>
  <div class="create-post">
    <label for="create-topic">Add topic: </label>
<br>
      <br>
    <input type="text" id="create-topic" v-model="topic" placeholder="enter" required>
<br>
    <br>
      <label for="create-price">Add a price: </label>
      <br>
      <br>
      <input type="text" id="create-price" v-model="price" placeholder="enter">
    <br>
      <br>
    <label for="create-location">Add a location: </label>
      <br>
      <br>
    <input type="text" id="create-location" v-model="location" placeholder="enter">
      <br>
      <br>
    <label for="create-provider">Add a provider: </label>
      <br>
      <br>
    <input type="text" id="create-provider" v-model="provider" placeholder="enter">
      <br>
      <br>
    <button v-on:click="insertPost">Create course</button>

  </div>
  <hr>
  <p class="error" v-if="error">{{ error }}</p>
<div class="posts-container">
  <div class="post"
       v-for="(post, index) in posts"
       v-bind:item="post"
       v-bind:index="index"
       v-bind:key="post._id">

    <br>

      <p>Course topic:</p>
    <p class="text">{{post.topic}}  </p>

    <p>Course price:</p>
    <p class="text"> {{post.price}}    </p>
    <p>Course location:</p>
    <p class="text">{{post.location}}  </p>
    <p>Created by:</p>
    <p class="text"> {{post.provider}}   </p>
    <button v-on:click="deletePost(post._id)">Delete course</button>
<br>
      <br>

<br>
      <br>
      <input  type="text"  v-model="post.topic"/>
      <input  type="text"  v-model="post.price"/>
      <br>
      <br>
      <input  type="text"  v-model="post.location"/>
      <br>
      <br>
      <input  type="text"  v-model="post.provider"/>
      <button v-on:click="updatePost(post)">Update course</button>
</div>

  </div>
</div>
</template>

<script>
    async updatePost({ _id: id, topic, price, location, provider }) {
              await postService.updatePost(id, topic, price, location, provider);
              this.posts = await postService.getPosts();
          },

</script>

index.js

const  express  = require ('express');
const  bodyparser  = require ('body-parser');
const  cors  = require ('cors');

const  app = express();

app.use(bodyparser.json());

app.use(cors({ origin: '*'}));
const posts = require('./api/posts');
const users = require('./api/users');

app.use('/api/posts', posts);
app.use('/api/users', users);

const  port = process.env.port || 5000;


app.listen(port, () => console.log(`Server started on port ${port}`));

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

Modify parameters variable when searching by utilizing bootgrid along with structured-filter

I have implemented both https://github.com/evoluteur/structured-filter and to develop an advanced search functionality using ajax/php. Initially, the code is functioning correctly and retrieves data from the php file. However, I am facing difficulties wh ...

Vue's keydown event will only fire when elements are in an active state

Encountering a strange issue while attempting to listen for keydown events in Vue.js. The keydown event is attached to a div tag that surrounds the entire visible area: <template> <div class="layout-wrapper" @keydown="handleKey ...

Unable to transmit form information using HTML/JavaScript/Express Node application

I'm facing a challenge in developing an app that allows me to input event information and then display it on a map. I'm encountering difficulties at the initial stage when it comes to saving the data. Even though Chrome's Inspect tool indica ...

Retrieve JSON information utilizing a specific value stored in the localStorage

After an extensive search online yielded no results, I decided to seek assistance here. This is what I have managed to gather so far: JSON I possess a JSON file containing various lists of words that require retrieval based on user input. The structure ...

The function service.foo is not recognized in Angular

My service function is not being recognized by my component import { Injectable } from '@angular/core'; import { ToastController } from '@ionic/angular'; @Injectable({ providedIn: 'root' }) export class LocationService { ...

The function will still be executed even if the assigned ID is not found within the document

I was working with the following javascript code: $(document).ready(function () { ... $("#mySelector").ready(function () { window.alert('What the heck!!!'); }); }); I expected a pop-up window to appear every time the mySel ...

Searching with MongoClient in Node.js requires specific querying methods to effectively retrieve data from a database

I need to extract specific data while excluding certain information. For instance: const details = [{ idn: 1, parent: 1 }, { idn: 2, parent: 2 }, { idn: 3, parent: 3 }] The desired output should be: const details = [{ idn: 2, ...

What is the best way to create a select box in React that allows for both single and multiple selections?

I recently started utilizing a new package for generating dynamic forms, which can be found at this link. Upon reading through the documentation, I attempted to create a select box as outlined in the instructions provided here. Despite following the step ...

Updating React component props

After updating the state in a component and passing the new props into the child, I noticed that the child is not updating correctly and the defaultValue of the input is not changing. My initial thought was that using this.props could be the issue, so I sw ...

What is the best way to develop interactive components using Google App Scripts for Google Sites?

I am currently working on building dynamic app script components that can be seamlessly integrated into my website, each with unique data for every instance of the script. I initially attempted using parameters but I'm uncertain if this is the most ef ...

Updating data from an ajax call in chart.js can be done with a few simple steps

I have successfully generated a graph using data from an ajax call in a php file. Now, I want to enhance this graph by allowing users to select a specific customer from a drop-down list (chg_customer) and display the corresponding count on the chart. Altho ...

Is it possible to determine the location of the "phantom image" while moving an object?

Is there a method to retrieve the location of the ghost image when an element is dragged? This is how the scenario is set up: <div id="test" v-on:dragstart="dragStart" v-on:drag="dragging" draggable="true" v-on:drop="drop" v-on:dragover="allowDrop"> ...

What is holding Firestore back from advancing while Firebase Realtime Database continues to evolve?

I am currently working on a chat application using Firebase within my Vue.js project. In this setup, I need to display the user's status as either active or inactive. To achieve this, I implemented the solution provided by Firebase at https://firebase ...

Using a directive to implement Angular Drag and Drop functionality between two tables with 1000 records

My code is functional, but there seems to be a delay in the appearance of the helper(clone) when dragging starts. I have two tables - one for the include list and another for the exclude list. Users can drag table rows from the include table to the exclud ...

Setting up Webpack and Babel for ReactJS development

Recently, I started delving into the world of ReactJS and stumbled upon a tool called webpack which acts as a module bundler. However, I've hit a roadblock while configuring it and keep encountering the following error message: ERROR in ./src/index. ...

The dropdown feature stores and displays only the initial value

After resolving my previous question (link), I am now facing a new issue where the value of the name field is only reflecting the first item in the dropdown list. Let me explain further. I have two dropdown menus, where selecting an option in one (A) dyna ...

Steps to customize Button Color and Label in a specific cell within a Material UI Table

I've implemented the Material Table to display my data, and it seems like this: In my code, I have a declared state as follows: const [sharedOrdersList, setShareOrdersList] = useState([]) When the User clicks the Share button, I push the Order Id in ...

Navigating through the complexities of managing asynchronous props and state in React-components

I'm really struggling to understand this concept. My current challenge involves passing asynchronously fetched data as props. The issue is that the props themselves are also asynchronous. Below is a simplified version of the component in question: i ...

Warning: Potential unhandled promise rejection in React class component

I'm trying to implement a promise inside a class so that depending on whether it resolves or rejects, another method of my component is executed. Below is the code I have: var promise = new Promise((resolve, reject) => { let name = 'DaveA&ap ...

Incorporate the block-input feature from sanity.io into your next.js blog for enhanced functionality

Currently, I'm in the process of creating a blog using next.js with sanity.io platform. However, I am facing some difficulties when it comes to utilizing the code-input plugin. What's working: I have successfully implemented the code component b ...