Encountering an issue while attempting to modify the user: receiving an error message stating "

Greetings! I am encountering an error when attempting to update a user on a page. The error message "Cannot POST /update-user" keeps popping up, indicating that there might be a mistake in the code. Can someone please take a look and help identify the issue? You can find the code below for reference. https://i.sstatic.net/54DDz.png

index.js

$('#add_user').submit(function(event){
    alert("Information saved!")
})

$('#update-user').submit(function(event){
    event.preventDefault();

let unindexed_array =$(this).serializeArray();
let data = {}
$.map(unindexed_array,function(n,i){
data[n['name']]= n['value']
})

console.log(data)

let request = {
    "url" : `http://localhost:3000/api/users/${data.id}`,
    "method" : "PUT",
    "data" : data
}

$.ajax (request).done(function(response){
    alert("User Updated!")
})

})

if(window.location.pathname == "/"){
    $ondelete=$(".table tbody td a.delete");
    $ondelete.click(function(){
        let id = $(this).attr("data-id")
   
        let request = {
            "url" : `http://localhost:3000/api/users/${id}`,
            "method" : "DELETE",
   
        }
   
   if(confirm("Are you sure you want to delete this record?")){
    $.ajax (request).done(function(response){
        alert("User deleted!")
    location.reload()
    })
   }
   
    })

}

ROUTER.JS

const express = require('express');
const route = express.Router()

const services = require('../services/render')
const controller = require('../controller/controller')

route.get('/',services.homeRoutes)
    
route.get('/add-user',services.add_user)
        
route.get('/update-user',services.update_user)
    
route.post('/api/users',controller.create);
route.get('/api/users',controller.find);
route.put('/api/users/:id',controller.update);
route.delete('/api/users/:id',controller.delete);

module.exports = route

_show.ejs

<%for(var i = 0; i <users.length; i++){%>

<tr>
    <td><%= i + 1%></td>
    <td><%=users[i].name%></td>
    <td><%=users[i].email%></td>
    <td><%=users[i].Lytis%></td>
    <td><%=users[i].status%></td>
    <td>
        <a href="/update-user?id=<%=users[i]._id%>" class="btn border-shadow update">
            <span class="text-gradient"><i class="fas fa-user-edit"></i></span>
        </a>
        <a class="btn border-shadow delete" data-id=<%=users[i]._id%>>
         <span class="text-gradient"><i class="fas fa-user-slash"></i></span>
     </a>
    </td>
</tr>
<%}%>

Struggling to troubleshoot and resolve the issue, despite trying various methods. It could be related to the ejs file or something else entirely. Also, seeking guidance on how to console log all details from the backend or frontend. Any assistance would be highly appreciated.

Answer №1

route.get('/update-user',services.update_user)

This route is initially defined as a GET request, but you are actually sending POST data to it. To fix this, update the route definition to:

route.post('/update-user',services.update_user)

$.ajax (request).done(function(response){

    console.log(response) <------------------------------------
    alert("User Updated!")
})

Answer №2

replace get with post on this particular line

route.get('/update-user',services.update_user)

and change it to

route.post('/update-user',services.update_user)

since you are using the post method for submission. Additionally, consider adding app.use(express.json()) and

app.use(express.urlencoded({extended:false}));
to your Express middleware.

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

Using double quotes in a label triggers a browser error displaying "Invalid Label"

Recently, I encountered issues with my browser while parsing JSON return data from the server. Initially, I assumed it was related to my specific data, but even a simple example like {"a": 1} led to an error "invalid label" in Firefox and "SyntaxError: U ...

Looking for a resolution? Ensure that actions are plain objects by employing custom middleware specifically designed for managing asynchronous actions

I'm attempting to replicate a MERN stack project named Emaily, but I've encountered an error Error: Actions must be plain objects. Use custom middleware for async actions. Here is the code for my Action: import axios from 'axios'; im ...

Load an external script once the page has finished loading by leveraging the power of $(document).ready() in conjunction with $.getScript()

Is it possible to load a script in the header of a website instead of at the bottom? I've been trying but it's not working as expected. Here is an example of what I'm attempting: HTML file: <!DOCTYPE html> <html lang="en"> < ...

Tips for sending a JSON string as a POST parameter without worrying about character encoding in Java

Attempting to send a POST parameter to my REST endpoint which is a JSON String containing special characters like double quotes ("). However, on the endpoint side, the string keeps getting encoded. This is the request section: HttpClient client = Htt ...

Having trouble implementing a transition on a dropdown menu in React

Can anyone help me troubleshoot an issue with adding a transition to a select box that appears when clicking on an input field arrow? I have tried implementing a CSS transition property, but it doesn't seem to be working. Any suggestions on what might ...

What are some reasons for the slow performance of AWS SQS?

My current project involves measuring the time it takes to send a message and receive it from an SQS queue. Surprisingly, the average time it takes is between 800-1200 ms, which seems like an excessively long period. Below is the code I have been using for ...

issue with returning value in React array mapping

I am currently working with the following function churnModel = () => { if (this.props.churnModel === undefined || this.props.churnModel.length === 0) { return("N/A") } else { this.props.churnModel.map((churn) => ...

Tips for ignoring preflight response in AngularJS

When I send a http.post request to my service, I start by sending an Option request as required by Cors. However, I've noticed that the OPTIONS (pre-flight) request does not return any response.data, whereas the POST request does. This creates an iss ...

Decoding a JavaScript object when receiving it as JSON through a POST request

While browsing through various SO posts, I came across the statement "javascript is JSON". However, I am struggling to apply this concept in my application. My issue arises when I try to perform a POST request using jQuery. $.ajax({ type: &apo ...

I am puzzled as to why Spring Data MongoDB does not include the "hint" option for Aggregate operations, although the mongodb Driver does have it. Unfortunately, I am unsure of how to properly utilize this feature

When it comes to performing aggregate operations, I often rely on MongoTemplate. However, I've noticed that it's not as efficient as I'd like it to be. I'm looking for a way to "hint" and specify my own index in order to improve perform ...

The jQuery ajax function functions flawlessly on a local environment, but encounters issues when used on a

After spending the entire day researching this issue, it appears to be a common problem without a solution in sight. The challenge I am facing involves using jquery's $.ajax() function to update database values through a service call. While it works ...

break LineSegment at specified location

Using the vertex positions provided below, I am creating a square using THREE.LineSegments (or even by a simple THREE.Line.) vertices: path.vertices = [ new THREE.Vector3( 3.4000015258789062, 0, 3.4000015258789062 ), new THREE.Vector3( 10.6000061 ...

Is it possible for a component to have multiple templates that can be switched based on a parameter?

Scenario My task is to develop a component that fetches content from a database and displays it on the page. There needs to be two components working together to create a single page, following a specific component tree structure. DataList - receives ful ...

Enhance Form within React Calendar

I have developed a calendar using React and Redux. When I click on an empty date, a modal pops up allowing me to add an event. However, I am struggling to implement the functionality to edit that event by clicking on it later. Can someone guide me on the c ...

Dynamic sizing of HTML elements

I'm currently developing a timeline feature using slick slider and I'm exploring ways to dynamically adjust the vertical line height for each event based on the text content. You can view the current timeline implementation at the following link ...

Updating multiple elements within an array in mongodb is a task that can be achieved

There is a Mongo document containing an array of elements. I need to reset the .handled attribute of all objects in the array with a .profile value of XX. The structure of the document is as follows: { "_id": ObjectId("4d2d8deff4e6c1d71fc29a07"), ...

Check for the presence of a certain value within an array and see if it corresponds to

array = ['data', 'category', 'hour']; object = { "status": { "type": "INFO", "messages": [] }, "data": { " ...

Tips for incorporating socket.io-stream in Angular applications

How can I integrate socket.io-stream into an Angular application? While we can easily use socket.io-stream in a web client with Browserify (https://github.com/nkzawa/socket.io-stream?tab=readme-ov-file#browser), it seems to not work as smoothly in Angular. ...

I'm getting a "module not found" error - what's the solution?

const { getIo } = require('services/socketio'); const restful = require('utils/restful'); const publicApiService = require('services/publicApi'); const accessTokenMiddleware = require('middleware/accessToken'); const ...

There was an issue with vite-plugin-pages stating that it could not locate the module '~pages' or its corresponding type declarations

Currently working on my Vue project, using TypeScript with Vite. To handle routing, I am utilizing the 'vite-plugin-pages' plugin. Encountered a type error while importing routes from the '~pages' directory. Here's a snippet of m ...