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

What is the advantage of not importing related modules?

As a newcomer to React, please excuse any novice questions I may have. I am currently utilizing npx create-react-app to develop a React app, but I'm unsure of the inner workings: Q1-If I were to throw an error in a component like so: import React, { ...

I am having trouble figuring out the reason why the node process keeps crashing on my Raspberry Pi 2

I've developed a Node program that utilizes the Selenium web driver to navigate through multiple URLs. However, I've noticed that I am not properly closing the web driver instance after each use. The program runs on a Raspberry Pi 2 for around ...

Preventing Vue.js SPA from accessing cached version when JWT expires: the solution

I'm encountering an issue with my Vue.js / Express application that I can't seem to resolve. Here's how the process unfolds: An unauthenticated user logs into the app and is presented with the login page. Once successfully authenticated, t ...

Change the left position of the sliding menu in real-time

I am currently designing a website with a sliding menu feature. By default, the menu is set to -370px on the left, displaying only the "MENU" text initially. When a user hovers over the menu, it expands to the right, allowing them to select different menu ...

What methods can I use to create a peer-to-peer communications platform with PHP, MySQL database, and JavaScript?

Currently, I am encountering the challenge of creating a communication channel between two users on a website (such as a gaming site) using only the technologies specified in the title. I recently created an online chess platform with the aim of allowing ...

If you click outside of a Div element, the Div element will close

I am looking for a way to implement a function that will hide a specific div when I click outside of its area. The div is initially set to Position: none and can be made visible using the following function: Div Element: <div id="TopBarBoxInfo1" oncli ...

What could be causing the lack of animation in W3schools icons?

I've followed the steps provided and even attempted to copy and paste them. However, I'm experiencing an issue where the animation doesn't fully execute. Instead of the bars turning into an X shape, they reset halfway through the animation. ...

Having trouble implementing table row selection with semantic-ui table

I am currently in the process of adopting Semantic-UI, but I am encountering some issues. Specifically, I am struggling to make row selection work in a table. Below is the sample HTML I am using from Semantic-UI: <table class="ui selectable celled tab ...

What is the process for adjusting the width of an element using JavaScript?

I have a unique bar with one half red and the other green. I am trying to subtract 1vw from the width of the red section. Unfortunately, using style.width is not yielding the desired result. See below for the code snippet I am currently using: //FIGHT do ...

What is the correct way to properly wrap the div component in this code snippet?

I am currently working on implementing a Javascript component that displays pinned locations and related information on a map. I have made some progress with the implementation, but unfortunately, it does not appear correctly in the actual site. There is a ...

Comparing strings with if-else statement

I am having trouble comparing strings in this array. For some reason, the strings are never equal. var person = ["Sam", "John", "Mary", "Liz"]; var searchedName = prompt("Enter name"); var resultMessage = ""; for (index in person) { var currentName = ...

Dealing with click events on layers with z-index positioning

In the map application I am developing, I have implemented 2 z-index layers. However, a problem arises when attempting to zoom in by clicking on these layers. The click handler is located on the lower z-index layer and I do not want it to execute when a co ...

Can the AJAX URL be loaded onto a new page?

https://i.stack.imgur.com/5l63v.pngPardon the poorly phrased question, but I need some guidance on a specific requirement regarding opening a URL in a new page. Currently, I have designed an AJAX URL and I'm wondering if it's possible to open thi ...

Query in progress while window is about to close

I'm attempting to trigger a post query when the user exits the page. Here's the code snippet I am currently working with: <script type="text/javascript> window.onbeforeunload = function(){ var used = $('#identifier').val(); ...

Personalizing/Concealing Navigation Controls

Looking for a way to customize the Navigation in the Pagination Plugin; changing 'First, Prev, Page 1, Page 2, Next, Last' to 'Prev, Next, Page 1 of 2' The documentation suggests using show_first_last set to false to hide 'First/L ...

How can we pass a function to a child component in Vue 2.0?

I am facing a challenge with passing a function link to the child component in Vue. Although it is functioning correctly, the code appears in HTML format. How can I enhance this? In my Vue instance, I have: app = new Vue({ ... some code data: { ...

It appears that Javascript variables are behaving in a static manner

I am currently building a PHP website with a registration page for users. I am implementing the LOOPJ jQuery Autocomplete script from to enable users to select their country easily. In this process, I encountered an issue where the value of another field ...

The functionality of an HTML form utilizing JavaScript struggles to function correctly when integrated with PHP

I created a form with JavaScript that allows me to toggle between different fields based on the selection made with radio buttons. <?php require_once 'resources/menus/adminMenu.php'; ?> <div class="col-lg-offset-3 col-lg-6 "> < ...

Error: Syntax mishap detected - Oh dear

Recently, I've been developing a small slideshow / public display for a client using the HTML5 Rock's Slideshow code. Everything was going smoothly until I encountered a DOM Exception 12 - an error related to CSS selectors. Strangely, I couldn&ap ...

Puppeteer throwing an error when querying selectors cannot be done (TypeError: selector.startsWith is not a supported function)

I recently installed Puppeteer and ran into an issue when trying to query a selector. I keep receiving a TypeError: selector.startsWith is not a function error. I attempted to resolve the problem by tweaking the core code and adding toString(), but unfort ...