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

Creating a personalized <select> filter in Angular.js with two different JSON choices

I am working with a Q&A JSON feed that includes the following: "questions": [ { "answer": "Ea et non sunt dolore nulla commodo esse laborum ipsum minim non.", "id": 0, "poster": "Chelsea Vang", "question": "Ex ex elit cu ...

Node.js tutorial: Fetching all pages of playlists from Spotify API

Currently, I am attempting to retrieve all of a user's playlists from the spotify API and display them in a selection list. The challenge lies in only being able to access 20 playlists at a time, which prompted me to create a while loop utilizing the ...

"Utilize jQuery to load a file when hovering over a specific

How can I dynamically load an external file using jQuery when a user hovers over a specific div? I attempted to load the file like a CSS file on hover but was unsuccessful. Is it possible to load a CSS file on hover as I've seen in some examples? $(d ...

Encountering Server Error 500 while trying to deploy NodeJS Express application on GCP App Engine

My goal is to deploy a NodeJS app on gcloud that hosts my express api. Whenever I run npm start locally, I receive the following message: >npm start > [email protected] start E:\My_Project\My_API > node index.js Running API on por ...

Utilize ES6 to import components for rendering on the server-side

In my ES6 React component file, I have a simplified version that utilizes the browser-specific library called store. Everything works perfectly fine on the browser: /app/components/HelloWorld.js: import React, { Component } from 'react'; import ...

Automatically rehydrate an instance using Angular and JavaScript

REVISION Special thanks to Shaun Scovill for providing an elegant solution using lodash // Creating an instance and injecting server object - within the ChartService implementation below var chart = new Chart(serverChartObject); // Replacing ...

Utilizing base classes in callbacks with ES6 in NodeJS

Consider this scenario where I have a class as shown below: class X extends Y { constructor() { super(); } method() { asyncMethod( function( err ) { super.method( err ); } ); } } The issue here is that super actually ...

Tips for enhancing the contents of a single card within a react-bootstrap accordion

Currently, I am facing an issue with my columns expanding all cards at once when utilizing react-bootstrap accordion. My goal is to have each card expand individually upon clicking on its respective link. However, I am encountering difficulties in implem ...

Performing an XMLHttpRequest to Submit an HTML Form

Our Current HTML Form Setup This is an example of the HTML form we are currently using. <form id="demo-form" action="post-handler.php" method="POST"> <input type="text" name="name" value=" ...

Tips for saving information in an array with Vue.js?

I am working on a task where I need to fetch data from an API and store only the values that are marked as "true" in a variable. The API response is listed below: API Output Data { "BNG-JAY-137-003": false, "BNG-JAY-137-004": true, ...

AngularJS combined with MVC is causing an issue where the table fails to refresh following an HTTP post request

When working with an $http.post() call and trying to update an HTML table in the success() callback, I encountered an issue: .success(function (data) { $scope.categories.push(data); }); Here is the HTML code for the table: <tbody> ...

Steps for storing div content (image) on server

Currently in the process of developing a web application that allows users to crop images. The goal is for users to have the ability to email the URL so others can view the cropped image, ensuring that the URL remains active indefinitely by storing every c ...

Getting React Developer Tools to Function with Webpack

I recently followed a tutorial on how to expose React as a global variable in Webpack using the Expose module. Despite installing the Expose module and adding the appropriate loader configuration in the webpack.config.js file, I am still unable to access R ...

What is the best way to manage an assertion error in MongoDB when using Node.js?

mongo.connect('mongodb://localhost',{useUnifiedTopology: true}).then((client) => { var db = client.db('complainbox'); db.collection('admin').findOne({"Email":req.body.Email},(err,result)=&g ...

Issue encountered when making API requests in JavaScript that is not present when using Postman

Currently, I am developing a web application using express and one of the functionalities is exposed through an API with an endpoint on 'api/tone'. This API acts as a wrapper for one of Watson's services but I choose not to call them directl ...

Button color changes upon submission of form

Can anyone help me figure out how to change the color of a submit button after a form submission using Twitter Bootstrap 3? I have a form with multiple buttons serving as filters for my product page, but I can't seem to change the color of the selecte ...

How to dynamically update the maximum y-axis value in Vue-Chart.js without having to completely re-render the entire

Currently, I am involved in a project that requires the implementation of various charts from the Vue-Chartjs library. One specific requirement is to dynamically change the maximum value on the Y-axis whenever users apply different filters. To achieve this ...

Why does this code snippet throw an error if let is not hoisted or in the temporal dead zone? It could have simply used the global reference instead

var b = 6; { console.log(b) let b = 55 } When running this code snippet, I encounter the following error message: ReferenceError: Cannot access 'b' before initialization Why is the console.log(b) not displaying 6 as expected? ...

Send a JSON string directly to Google Cloud Storage without the need for a file upload

When I need to receive data in the form of a JSON string from an external source and then upload it directly to Google Cloud Storage without saving it as a local file first, is there a way to accomplish this task? Thank you. storage .bucket(bucketName) ...

Pass the validation errors from Laravel controller to Vue component

Hello everyone, I'm in need of assistance with returning error validation for the following code implemented in Vue: Validator::make($request->all(), [ 'title' => 'required|unique:posts|max:255', 'body' =&g ...