How do I redirect with a GET method after calling the *delete* method in Node / Express server?

As someone new to AJAX and Node, I encountered a dilemma that I hope to get some guidance on. Here's the issue: I have a DELETE ajax call that removes a row from the database and I want to redirect back to the same route with a GET method afterwards. However, I'm unsure whether I should handle the redirect from the front-end script or using another strategy. Any advice would be greatly appreciated!

Front-end JavaScript for making the Ajax call (script.js)

$('.deleteRepository').on('click', function(event) {    
event.stopImmediatePropagation();
var username = $(this).attr('username');
var repoName = $(this).attr('repoName');
var oReq = new XMLHttpRequest();
oReq.open("delete", "/user/"+username+'/'+repoName);
oReq.send();
});

myRoute.js

router.route('/:username/:repository')
.delete(function(req, res) {
console.log('\n\nDelete method called\n\n');
let username = req.params.username;
let repoName = req.params.repository;

deleteRepositoryFromUser(req, res)
.then(function() {
console.log('deleted, now redirect');
//I want to redirect to this page using GET, but logs DELETE
//I also want to redirect to /user/TonyStark/Favorites
res.redirect(200, '/user/'+username+'/Favorites'); 
})

Console Output

GET /user/TonyStark/delMe 200 114.702 ms - 4075
...    

Delete method called


deleteRepositoryFromUser()
repoName: delMe
username: TonyStark
deleted, now redirect
DELETE /user/TonyStark/delMe 200 4.568 ms - 44 //how can I make GET?
//why is it not going to /user/TonyStark/Favorites?

Answer №1

There is an error in this line of code

res.redirect(200, '/user/'+username+'/Favorites');
. Redirecting with a status code of 200 is incorrect. The appropriate status codes to use for redirection are either 301 or 302. For more information on HTTP status codes, you can refer to the following link: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

Answer №2

If you need to manually change the HTTP method to GET before performing a redirect, you can do so in your myRoute.js file:

router.route('/:username/:repository')
.delete(function(req, res) {
  console.log('\n\nExecuting Delete method\n\n');
  let username = req.params.username;
  let repoName = req.params.repository;

  deleteRepositoryFromUser(req, res)
    .then(function() {
      console.log('Deleted successfully, now redirecting');

      //Changing the HTTP method to GET explicitly
      req.method = "GET"

      res.redirect(200, '/user/'+username+'/Favorites'); 
    })

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

Step-by-step guide on starting a node.js server using a custom command

Is there a way for me to create a JavaScript file that automatically executes the command node --max-old-space-size=1024 index.js so I don't have to type it out every time? I'm thinking of a file like start.js that runs the command as soon as I l ...

Retrieve JSON information from a URL via AJAX if applicable

Is there a way to retrieve the JSON data from the following URL and incorporate it into my webpage in some capacity? (Disclaimer: I do not own this website, I am simply utilizing the data for a basic free app.) Although entering the URL directly into the ...

Can we split the PHP Photo Gallery into a second page after displaying 12 images?

I recently developed a simple PHP photo gallery for my website that pulls data from a MySQL database. By using a while loop, I am able to display three images (from ID 1 to 3) in a single row, continuing this pattern until a total of 12 images are shown. ...

Challenges with ReactToPrint Library and Optimizing Layout for Thermal Printer

Working on a React.js project, I have been using the ReactToPrint library to print a specific section of my page. However, I am facing an issue where the page size remains too large and important content is being left out in the printed receipt. It seems ...

Converting URL-esque information to JSON using JavaScript

Does anyone have a solution for converting an array of URL-like data into JSON format? For example, how can we convert the array ["a.b.c.d", "a.c.e.f", "a.b.c.g"] into the following JSON structure: items:{ text: "a", items:[ { ...

Guide on setting up and configuring the seeder in MikroORM

Hey there, I recently tried to execute seeders in MikroORM and encountered a problem. I followed all the steps outlined here: . In the MikroORM route folder (alongside mikro-orm.config.ts), I created a seeders directory. I updated mikro-orm.ts with the fo ...

Transferring token values between collections in POSTMAN - AUTOMATION | NEWMAN: A step-by-step guide

My goal is to streamline my unit test cases by utilizing the POSTMAN Collections API & NEWMAN. I successfully created two test cases that are performing as expected. Upon exporting the collection from POSTMAN, I proceed to generate the test report using NE ...

How to utilize AJAX to input data into a MySQL database using PHP in a multi-step form

Hi there, I'm currently working on a project that involves inserting data into a MySQL database using PHP and AJAX with multiple forms on a single page. The insertion process is functioning correctly, but I'm facing an issue where the data from ...

The Node.js application is unable to execute due to the error: "View "error" could not be found in the views directory."

Currently, I am following a tutorial that covers the integration of social login with Passport and Node. You can find the tutorial here: Tutorial Link In line with the tutorial, I have started working on a project while utilizing Windows 10 operating syst ...

Using codedeploy to deploy a Next.js application onto an AWS EC2 instance

After creating a fresh NextJS app with only basic boilerplate files and folders, I uploaded it to a CodeCommit repository. I already had a functional CodePipeline and simply switched the Source stages. However, I am encountering deployment failures during ...

Twice the clicking actions triggered by the event

Whenever I try to trigger a function by clicking on the label text, the click event seems to be firing twice. HTML <label class="label_one"> Label One <input type="checkbox"/> </label> However, if I modify the HTML code as f ...

Issue encountered when attempting to utilize multiple datasets with Twitter Typeahead/Bloodhound

Hello, I am currently learning how to use Typeahead and Bloodhound with the latest javascript. Below is a snippet of my code: Html: <div id="multiple-datasets"> <input class="typeahead" type="text" placeholder="NBA and NHL teams"> </div ...

The declaration for "Control" is not present, possibly being restricted by its protection level

I'm really struggling to get the jQuery datepicker working in ASP.NET. I've tried various examples, but nothing seems to work for me. Even though I'm fairly new to ASP.NET, I am learning quickly! Here is the script I am trying to use: < ...

Error message in JS/Ajax alert box

I keep receiving an alert box saying "Image uploaded" even when the variable $imagename is empty. Below is the script in question: <script> function ajax_post1(ca){ var cat = ca; var name = document.getElementById("name").value; var ...

AngularJS: The image loader will display on the initial div

I am trying to implement a loader that will hide after a certain amount of time when the user clicks on a profile. I have used a timeout function to achieve this behavior. However, the loader is appearing on the left side instead of within the respective ...

Using Sequelize to Link Two Columns Between Tables

In my sequelize database, I have the following table settings: const Accounts = sequelize.define('Accounts', { name: DataTypes.STRING, }); const Transfers = sequelize.define('Transfers', { value: { type: DataTypes.DECIMAL(10, ...

Attempting to reset the altered values proves ineffective in different Ctrl instances within AngularJS

I'm feeling a bit disoriented regarding my current issue. The scenario involves two views and a controller that interact with a service. The first view consists of a table list containing items loaded from a WebAPI. The service sends requests to the s ...

Using Ajax, jQuery, and PHP in Internet Explorer 9 is possible, but it may not work in Internet

I am encountering an issue with my jQuery/AJAX script that posts to a php file in order to retrieve XML data. The problem arises when I print the data and notice that all the HTML source code is being returned instead of properly parsed XML, especially in ...

how to bind data to an array in Angular

I recently developed an Angular 7 application that features the capability to dynamically add and remove controls. However, I am facing challenges when it comes to binding the data to the form. In the code snippet below, I am focusing on the process of ad ...

What is the best approach to manage various json data specific to each jquery tab?

Within my webpage, I am utilizing three different (jQuery) tabs: Overview Pricing Destination info Each of these tabs houses completely unique sets of data. By specifying a URL in the href attribute, I can trigger an AJAX call to retrieve this data. How ...