How come I can successfully test the delete functionality in Postman, yet encounter issues when trying it in the browser?

While testing my HTTP delete request in Postman, everything ran smoothly. However, when I attempted to test it in the browser, I encountered a 'Cannot GET /account/delete/Julieth' error. To address this issue, I modified the method to GET, which resolved the problem in both environments. Yet, I am puzzled as to why the DELETE method is not recognized by the browser. Are there specific constraints that prevent the browser from acknowledging the DELETE method?

Here is the code snippet from index.js:

var express = require("express");
var app = express();
var cors = require("cors");

var bodyparser = require("body-parser");
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json({ limit: "10mb" }));

//serve static files
app.use(express.static("public"));
app.use(cors());

let users = [
  {
    name: "Julieth",
    lastName: "Bautista",
    Email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cba1bea7a2aebfa38ba6a2bfe5aeafbe">[email protected]</a>",
    password: "bigsecret",
    balance: 0,
  },
  {
    name: "Jose",
    lastName: "Bautista",
    Email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4bebba7b194b9bda0fab1b0a1">[email protected]</a>",
    password: "secret",
    balance: 233,
  },
];

//create user route. GET should only retrieve data.
app.get(
  "/account/create/:name/:lastname/:email/:password/:balance",
  function (req, res) {
    res.send({
      name: req.params.name,
      lastName: req.params.lastname,
      email: req.params.email,
      password: req.params.password,
      balance: req.params.balance,
    });
  }
);
//GET should only retrieve data.
app.get("/account/logIn/:email/:password", function (req, res) {
  res.send({
    email: req.params.email,
    password: req.params.password,
  });
});

app.get("/account/all", function (req, res) {
  res.send(users);
});
//post often causing a change in state or side effects on the server.
app.post("/account", function (req, res) {
  var balance = req.body.balance;
  const user = req.body.name;
  const password = req.body.password;
  users.push({ name: user, password: password, balance: balance });
  res.send(users);
  console.log("balance:" + balance);
});
//PUT replaces all current representations of the target resource with the request payload.
app.put("/account/withdraw", (req, res) => {
  console.log(users);
  const newArray = users.map((user) => {
    if (user.name == req.body.name && user.password == req.body.password) {
      if (user.balance == 0) return;
      else {
        newBalance = user.balance - req.body.balance;
        user.balance = newBalance;
        let myUser = user;
        let updatedUser = { balance: newBalance, ...myUser };
        user = updatedUser;

        return user;
      }
    }
    return users;
  });

  res.send(users);
});
app.put("/account/deposit", (req, res) => {
  console.log(users);
  const newArray = users.map((user) => {
    if (user.name == req.body.name && user.password == req.body.password) {
      newBalance = req.body.balance + user.balance;
      user.balance = newBalance;
      let myUser = user;
      let updatedUser = { balance: newBalance, ...myUser };
      user = updatedUser;

      return user;
    }
    return users;
  });

  res.send(users);
});

//deletes the specified resource.
app.get("/account/delete/:name", function (req, res) {
  console.log(users);
  let filteredArray = users.filter((user) => user.name !== req.params.name);
  users = filteredArray;
  res.send(users);
  res.sendStatus(204);
});

//indicate that the specified resource will be deleted, however doesn't work in browser
app.delete("/account/delete/:name", function (req, res) {
  console.log(users);
  let filteredArray = users.filter((user) => user.name !== req.params.name);
  users = filteredArray;
  res.sendStatus(204);
});

app.listen(3000, function () {
  console.log("Runing on port 3000!");
});

To overcome the issue, I temporarily switched the method to GET and ensured cross-origin requests were allowed. Despite these adjustments, do you have any suggestions on resolving the problem without converting DELETE to GET for proper identification by the browser?

Answer №1

It appears that you are attempting to search a URI using the browser, which is not supported. Browsers can only utilize the GET method for this purpose. To perform a DELETE action, you will need to use a library such as fetch, axios, ajax, etc. (assuming you are working with react or jquery).

Alternatively,

You can execute the following code in the developer tools console:

 fetch('/account/delete/anyname', {
  method: 'DELETE'
})
.then(response => response.json()) 
.then(data => {
  console.log(data);
})
.catch(error => {
  console.error("Error From server:", error);
});

Answer №2

The error message indicates that you are trying to execute a GET request. For the browser to process DELETE requests correctly, they must be sent using JavaScript.

Here is an example:

fetch('/delete/profile/JohnDoe', {
  method: 'DELETE'
})
.then(response => response.json()) 
.then(data => {
  console.log(data);
})
.catch(error => {
  console.error('Error:', error);
});

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

The CSS in Node.js stubbornly refused to be implemented

I'm in the process of creating a straightforward application, and while setting up the project, I encountered an issue. I have a basic localhost server and an HTML file to display, but upon accessing the localhost, I received this error in the console ...

Having trouble with the select feature in OpenLayers? The selected feature isn't highlighting as expected

When searching for a feature by its attribute, the issue arises where the feature is not highlighted. A popup appears, but the selected feature remains unhighlighted. Below is the code being used: this.showparcel = function(getpin){ for(var f ...

What are the steps for running app.js deployed on a remote server using the local bash terminal?

After launching my web application on GoDaddy, which is built in Node.js, I have encountered a dilemma. In order to run app.js, I currently rely on my computer's bash command prompt. However, this poses an issue - if I were to shut down my laptop, the ...

Is the hook useEffect behaving improperly due to dependency issues?

I'm facing an issue with an infinite loop occurring inside the useEffect hook. I want to trigger a new request only when the id dependency changes. However, when I don't pass data, I encounter problems with updating the state using setData. On th ...

Using AngularJS to pass objects dynamically through ng-include

Below is an example that is fully functional, except for one issue. When using node.title within the HTML code, everything works as expected. However, when trying to use {{node.title}} within the ng-include file, it does not function properly. Only the g ...

Creating a reliable and secure profile using Javascript

I am currently utilizing the server-side implementation of Reliable Secure Profile for HTTP/S push in .NET 4 and I am interested in finding out if there is a JavaScript client available. ...

Error in Angular multiselect dropdown: Unable to retrieve the length of undefined property

counter: number = 0; getDatatypes(){ if(this.counter == 0) { if(this.appId != 0) { if(undefined != this.datatypes && this.datatypes.length) for (let i = 0; i < this.datatypes.length; i++) { this.ap ...

The problem with JQuery ajax arises when attempting to send a file input value

I am facing an issue when trying to send a file value to PHP using the ajax code below. The file gets uploaded successfully and stored in the database, but the problem arises when I get redirected. // form data submission $('#myForm').submit(fun ...

Perform a toggle action on the first row when clicking within the current row using Jquery

I've been grappling with the idea of creating a function that can display and hide a comment field when a button is clicked. The challenge here is that there are multiple line items with their own comment boxes. I want to find a way to achieve this wi ...

A selection dropdown within a grid layout

Hey there, I am currently working on implementing a dropdown list within a data grid. I want to ensure that if I select a value in one row of the dropdown and then select the same value in another row, a message will be displayed saying 'already added ...

What is the best way to send props from page.js to layout.js in the Next.js app directory?

Is there a way to effectively pass props to layouts in Next.js 13? Can we optimize the approach? Here's an example: // layout.js export default Layout({children}) { return ( <> {/* Display different `text` based on the page.js being ...

The page you're looking for is nowhere to be seen on the Angular Routing for Mobile View - it seems to have vanished into thin

After creating an angular app, I encountered an issue while using ng build --prod to build it for production and hosting. On the mobile view, every routing except the homepage displayed a 404 Page Not Found error. I am currently unable to determine the roo ...

Select2 - Issue with AJAX causing search results to not display in dropdown

Currently using Select2 version 4.0.1. Implemented ajax to display results based on user input, but facing an issue where Select2 does not list any results despite receiving the proper response from ajax. Additionally, the input box loses focus after the ...

Having trouble finding a solution to prevent code from automatically adding a class in jQuery/JavaScript?

I am currently in the process of customizing the FlexNav Plugin. I have made a modification to allow sub-menus to open on click instead of hover. However, a new issue has arisen where it requires two clicks to open a submenu. Upon investigation, I have i ...

Vue Error: The function slugify is not defined

Currently, I am working on a feature where I want to extract the value from one input field, convert it into a slug format, and display it in another input field. This project involves Laravel Spark, Vue, and Bootstrap 4. Here is the content of my listing ...

Setting focus on the require attribute for the <input> tag in a React application

I have a login/register form with multiple input tags. My goal is to automatically set focus and require attribute on the first input tag when the form is opened. I have tried using jQuery and JavaScript to add the required attribute, which works fine. H ...

A subtle X icon tucked away in the corner of the homepage, a result of the jquery modal window

Struggling with an issue on a client's website - there are multiple jquery sections with buttons that open modal windows. The problem is that the close button for these modals appears on page load and is situated at the top right of the homepage. Is t ...

What is the most effective method for declaring callbacks on objects in Typescript?

I am currently working on a sidebar menu component that is connected to a service holding items in the menu. This allows multiple sources to make alterations to the menu as needed. Each item in the menu currently follows the SidebarItem interface: export ...

Saving the data received from an Ajax success call into a JavaScript variable for future use in another JavaScript function

Currently, I am working on a login form that interacts with a database containing usernames and passwords. I have successfully implemented a comparison method to check if the entered username and password match those stored in the database. However, I woul ...

Adding a Vue component to HTML using a script tag: A step-by-step guide

Scenario: I am working on creating a community platform where users can share comments. Whenever a comment contains a URL, I want to turn it into a clickable component. Challenge Statement: I have a dataset in the form of a string and my aim is to replac ...