I am experiencing an issue where the Mongo item ID is not being successfully passed through the REST API

Recently, I've been working on developing a blog site for my class project. The main goal is to create a REST API for the blog site. I have successfully managed to display data from the database using .ejs views, except for one issue. I am facing difficulty in pushing the blogID through when it comes to updating a specific blog with a submit button. I've spent the last 6 days tirelessly searching and testing various solutions but haven't made progress. If anyone could take a look at my code and provide assistance, I would greatly appreciate it. Thank you.

<form method="put" action="/blogedit/<%= blogData.blogid %>" style="padding: 20px;">
    <div class="form-group">
      <label for="blogTitle"  class="text-dark">
          Blog Title
      </label>
      <input class="form-control"  id="blogTitle" name="blogTitle" value="<%= blogData.blogTitle %>">
          <label for="blogText" class="text-dark" style="width: 100%;">
              Blog Text
          </label>
          <input class="form-control" id="blogText" name="blogText" value="<%= blogData.blogText %>"></textarea>
           </div>
         <input type="submit" class="btn btn-dark" value="Save">
      </div>
   </form>

This snippet shows the HTML form that I am attempting to submit.

/*GET BLOG EDIT PAGE*/
module.exports.readOne = function (req, res) {
    var requestOptions, path;
    path = "/api/blog/" + req.params.blogid;
    requestOptions = {
        url: apiOptions.server + path,
        method: "GET",
        json: {}
    };
    request(
        requestOptions,
        function (err, response, body) {
            if (err) {
                console.log(err);
            } else {
                console.log(response.statusCode);
                renderBlogEdit(req, res, body);
            }
        }
    );
};

/*Render BLOG EDIT PAGE */
var renderBlogEdit = function (req, res, blogData) {
    res.render('blogedit', {
        title: 'Edit Blog',
        pageHeader: {
            title: 'Edit Blog'
        },
        blogData: blogData,
        blogid: blogData._id,
        blogTitle: blogData.blogTitle,
        blogText: blogData.blogText
    });
};
/*Blog Edit Post*/
module.exports.editPost = function (req, res) {
    var requestOptions, path, postdata;
    path = '/api/blog/' + req.params.blogid;

    postdata = {
        blogTitle: req.body.blogTitle,
        blogText: req.body.blogText
    };

    requestOptions = {
        url: apiOptions.server + path,
        method: "PUT",
        json: postdata
    };
    request(
        requestOptions,
        function (err, response, body) {
            if (response.statusCode === 201) {
                res.redirect('/bloglist');
            } else {
                _showError(req, res, response.statusCode);
            }
        }
    );
};

The above content showcases the app_server controller used for editing a blog, while below you'll find the app_api function specifically designed for editing blogs.

module.exports.readOne = function (req, res) {
    console.log('Finding blogs', req.params);
    if (req.params && req.params.blogid) {
        blogSch
            .findById(req.params.blogid)
            .exec(function (err, blog) {
                if (!blog) {
                    sendJsonResponse(res, 404, {
                        "message": "blogid not found"
                    });
                    return;
                } else if (err) {
                    console.log(err);
                    sendJsonResponse(res, 404, err);
                    return;
                }
                console.log(blog);
                sendJsonResponse(res, 200, blog);
            });
    } else {
        console.log('No blogid in request');
        sendJsonResponse(res, 404, {
            "message": "No blogid in request"
        });
    }
};

module.exports.editOne = function (req, res) {
    console.log("Updating Blog Entry : " + req.params.blogid);
    console.log(req.body);
    blogSch.findOneAndUpdate(
        { _id: req.params.blogid },
        { $set: { "blogTitle": req.body.blogTitle } },
        { $set: { "blogText": req.body.blogText } },
        function (err, response) {
            if (err) {
                sendJsonResponse(res, 400, err);
            } else {
                sendJsonResponse(res, 201, response);
            }
        }
    );
};

If anyone can offer any help or guidance, it would be highly appreciated. Whenever I click the submit button on the form, I keep encountering a 404 error indicating the page cannot be found. Thank you very much for your assistance!

Answer №1

Upon first inspection, it appears that there is an issue with the HTML structure of your form. In HTML5, a form can only utilize the methods 'POST' and 'GET'. The presence of PUT in your code is causing the form to default to a GET request, leading to the display of the 404 error page.

To resolve this issue, make sure to update both the HTML5 form and the server to use the POST method instead.

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

Issue with AngularJS: The select dropdown fails to update the selected option when the bound scope variable changes

I am facing an issue with a select control in my Angular app. The options for the select are generated dynamically from an array of objects in the scope. When I try to pre-select a specific option on app init by changing a bound variable on the scope, it d ...

Decipher complex JSON structures

I am working with a multi-level JSON structure: { "1":{ "name":"PHP", "slug":"/tag/php", "type":"Tag" }, "2":{ "name":"JavaScript", "slug":"/tag/javascript", "type":"Tag" }, "3":{ ...

Is the side tab overflowing the window due to its absolute positioning?

My browser window has a side tab that slides in when clicked using jQuery. The issue I'm facing is that the tab overflows the body due to its absolute positioning. However, the overflow stops when the tab is pulled in by jQuery. It only happens when t ...

Is there a way to choose multiple IDs in this code that all share a common word?

I'm attempting to target several duplicate ids such as "img1, img2" in my code, but I haven't had any success. How can I select all the ids that contain the same word without relying on jQuery or any other external libraries? Below is the code s ...

What is the proper way to retrieve a constant variable within a return statement?

Here is the code I have written: const keyToDisplayMessage = 'REGULAR_HOME'; const cf = format( { accountName: this.accountName, }, this.pageData.sucessMessages.keyToDisplayMessage, this.$route.name ); return cf; The ...

The troubleshooting of a find method in Mongoose

Why is it necessary to use await twice when calling the model function, even though we already used await in the model itself: async function model() { return await data.find({}, '-_id -__v') } When I console.log await data.find({}, '-_id ...

How to Send C# Array as a Parameter to a JQuery Function

I'm currently working on passing a C# array to a JQuery function as a parameter. The C# code I have to call the function is: //Create an Array from filtered DataTable Column var GatepassIDs = defaultView.ToTable().AsEnumerable().Select(r => r ...

API Post request encountering fetch failure

The route "/api/users/register" on my express server allows me to register an account successfully when passing data through Postman. However, when trying to register an account using the front-end React app, I'm encountering a "TYPE ERROR: Failed to ...

Only the main page is accessible quickly through Express

Currently, I am delving into learning Express and leveraging FS to load my HTML Page. My research on this topic only led me to references of using ASP.NET instead of Express. Here is a snippet from my Server.js file: var express = require('express&a ...

What is the best way to retrieve the dimensions of a custom pop-up window from the user?

Currently, I am in the process of developing a website that allows users to input width and height parameters within an HTML file. The idea is to use JavaScript to take these user inputs and generate a pop-up window of a custom size based on the values pro ...

Order of execution behavior

I am currently working on a function that, when triggered, will populate the webpage with dynamic tiles. These tiles retrieve data from a remote database through an AJAX request and utilize jQuery 3.0 in the implementation. Function Implementation: funct ...

Determining the appropriate generic type in Typescript

In my code, there is a method designed to extend an existing key-value map with objects of the same type. This can be useful when working with database query results. export function extendWith< T extends { id: string | number }, O = | (T[" ...

Updating a field in a MongoDB document with a different set of JSON data

Let's say I have a MongoDB table structure similar to this: { "_id": ObjectId("531963b60748a6078fe4f345"), "acces": "172.1.6.2.18", "adapter": "Win 9", "flavour": "LokiSnap", "jobid": "8", "os": "VM-WIN7-32", "results": "" ...

The ancient oracle of Delphi and the modern login portal of Microsoft

I need to login to a site that utilizes . To streamline the process for end-users, I want to store credentials in an .ini file and inject them into a two-stage JavaScript online prompt. Is there a way to have Delphi run a program with a browser that auto ...

Can asynchronous programming lead to memory leakage?

I'm wondering about the potential for memory leaks in asynchronous operations, specifically within Javascript used on both frontend and backend (node.js). When the execute operation is initiated, a delegate named IResponder is instantiated. This dele ...

What is the reason behind the unnecessary requirement of adding {...props} when passing them to a component in a React router?

Recently, I delved into learning React and encountered a puzzling issue while following a course. To gain clarity, I decided to experiment with it separately, but the confusion remains unresolved. While researching, I discovered that when utilizing a Rout ...

Refresh the content of a webpage in AngularJS without the need to fully reload the entire page

Within my controller and view files, I have content that is sourced from various places, including API calls. For instance, I have information retrieved from the database where users can update certain details like their last name. After submitting the up ...

Discovering, storing, and displaying JSON data in JavaScript

I am currently working on a PHP file called rows2.php that displays results from a database by showing the new id of the field in this format: {'new_id':'92'} My goal is to use JavaScript to load this data and add the new_id surrounded ...

How to dynamically reset an ng-form in Angular

After reviewing the following resources: Reset Form in AngularJS and Angular clear subform data and reset validation, I am attempting to develop a flexible form reset/clear function that would resemble the code snippet below: $scope.clearSection = functio ...

Guide on how to assign a masterpage DOM element to a content page using JavaScript

Within an ASP.NET master page, there is a specific div element that I want to hide in one of its content pages. To achieve this, I included the following JavaScript code at the end of the content page: if (document.getElementById('sitemap')) { ...