Troubleshooting a deletion request in Angular Http that is returning undefined within the MEAN stack

I need to remove the refresh token from the server when the user logs out.

auth.service.ts

deleteToken(refreshToken:any){
    return this.http.delete(`${environment.baseUrl}/logout`, refreshToken).toPromise()
  }

header.component.ts

refreshToken = localStorage.getItem('refreshToken')
logout = async()=>{
    try {
      console.log(this.refreshToken)
      await this.authService.deleteToken({refreshToken:this.refreshToken})
      localStorage.removeItem("refreshToken");
      localStorage.removeItem("token");
      this.router.navigateByUrl('/login');

    } catch (error) {
      console.log(error)
    }
  }

The console.log(this.refreshToken) displays the token retrieved from local storage correctly.

Backend authController.js

exports.deleteToken = async (req, res) => {
   try {
        let user = await User.findOne({ refreshToken: req.body.refreshToken })
        console.log(req.body.refreshToken)
        if (req.body.refreshToken == user.refreshToken) {
            await user.updateOne({ $unset: { refreshToken: "" } });
            res.sendStatus(200);
        } else {
            res.status(400).json({ message: "Error while deleting token" })
        }
    } catch (error) {
        console.log(error)
    }
}

When I output req.body.refreshToken using console.log, it appears as undefined.

Answer №1

In the scenario where this solution proves to be correct, it is important to note that the delete request does not include a body. Therefore, the request should follow this format:

deleteAuthToken(refreshToken:any){
    return this.http.request('DELETE', `${environment.apiUrl}/logout`, {
      body: { tokenToRefresh: refreshToken }
  }).toPromise();
  }

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

Enhance user interface dynamically with additional components in ReactJS by rendering them onClick. Master the optimal

Just started using React and I'm really enjoying it. I have a scenario where the parent component renders both: A TagBuilderContainer (which contains initially 1 TagBuilderComponent) An "Add Tag" button with an onClick event (intended to add a new ...

Having difficulty resolving rxjs issue

Compilation failed. Failed to locate module './rxjs/Observable/of' in 'C:\Users\Admin\angular\myheroes\src\app' @ ./src/app/hero.service.ts 13:11-40 @ ./src/app/app.module.ts @ ./src/main.ts @ multi ...

Tips for effectively creating and appending elements using JavaScript

Code Sample var result=$.getJSON("http://search.twitter.com/search.json?callback=?",{q:query}, function(data) { ... question. }); Query: In order to display each tweet result, I want to ...

What is the process for obtaining authorization to access user information?

I am facing a perplexing issue with my app settings. Despite setting everything up correctly, I am unable to authenticate my account on my website using the Javascript SDK. Whenever I try to console.log(me), I only receive public information. Upon furthe ...

Error in Angular 6: There is no property '$' on the type 'Window'

I've been facing an issue while trying to integrate jQuery and jsGrid into my Angular 6 project. The project won't compile unless I comment out a specific part of the code. Once I do that, the compilation works, but I still encounter an error. I& ...

Error encountered while deploying to Heroku: cross-env not detected in Node.js application

As I attempt to deploy my project on Heroku, the following error persists despite all my efforts. Please assist me in resolving this issue: { "name": "storybooks", "version": "1.0.0", "des ...

What is the most efficient way to combine a parameter string within a JavaScript function and append it to an HTML string?

Welcome to my HTML code snippet! <div id="content"></div> Afterwards, I add an input to #content: $( document ).ready(function() { // Handler for .ready() called. var parameter = "<p>Hello</p>"; $("#content").appe ...

To access the link, simply click once if there is no child menu. However, if there is a child menu attached, be sure to click

I am working on a mobile menu that is designed to slide out when clicked. Currently, the parent pages are displayed by default. I want to implement functionality where if a parent page has child pages, clicking on it will slide down the sub menu. If click ...

How can you prevent videos from constantly reloading when the same source is used in multiple components or pages?

How can we enhance loading performance in Javascript, React, or Next JS when utilizing the same video resource across various components on different pages of the website to prevent unnecessary reloading? Is there a method to store loaded videos in memor ...

What is a way to hide or exclude tabs when there is no content to display for a particular tab in Vue?

I'm new to javascript and Vue, and I'm trying to figure out how to hide tabs that don't contain any information. I want to display only the tabs that do have information. Can someone please help me with this? I automatically pull images bas ...

What is the best way to set up a session using jQuery?

I've been troubleshooting my code and I can't seem to figure out why the jquery.session.js file isn't working. Can someone help me find a solution? $.session.set('rmng_time', remaining_seconds); alert("j session "+$.sessi ...

Using JavaScript in PHP files to create a box shadow effect while scrolling may not produce the desired result

Issue at hand : My JavaScript is not functioning properly in my .php files CSS not applying while scrolling *CSS Files are named "var.css" #kepala { padding: 10px; top: 0px; left: 0px; right: 0px; position: fixed; background - c ...

Having trouble updating properties of child components in Angular

I have a data filtering functionality where I enter values in a filter popup and successfully retrieve results. I then store this data in local storage to retain it when navigating back from another page. However, upon returning to the filter component, I ...

What could be causing my YAML value to be undefined when I try to read it in JavaScript, despite it being defined in every other

I have been attempting to access a YAML file from my local directory. While I am able to read the file, the data within it appears to be undefined. The error message that I am encountering is as follows: https://i.sstatic.net/yXC0H.png Here is an exampl ...

Array data causes tabs to be shown incorrectly

My attempt to create tabs similar to those in this tutorial has hit a snag. While I can easily display hard coded tabs, I'm facing issues when trying to populate the tabs from a list as they end up being displayed incorrectly. Here is the code and im ...

Accessing XML data using Cross-Domain AJAX

New to this! I'm currently working on a client script that requires reading an XML file from another domain. I attempted to utilize JSONP, and while I receive a 200 response, the client is unable to access the data returned for some unknown reason. Tw ...

During the initial render in next-auth, the useSuspenseQuery function is triggered to fetch data without a defined token, resulting in an

Recently, I've started implementing the new useSuspenseQuery feature from react-query and I couldn't help but notice that the enabled property is missing on this hook. This has caused an issue with my useGetApiToken function, as it initially retu ...

What is the process for extracting context or span from an incoming http request in NodeJS without relying on automated tools

I am currently in the process of transitioning my Node.js application from using jaeger-client to @opentelemetry/* packages. Within my Node.js application, I have a basic http server and I aim to generate a span for each response. Previously, with jaeger ...

React Material UI DataGrid: Error encountered - Unable to access property 'useRef' due to being undefined

The challenge at hand Currently, I am faced with a dilemma while attempting to utilize the React DataGrid. An error in the form of a TypeError: Cannot read property 'useRef' of undefined is appearing in my browser's stack trace. Steps take ...

Enclosing Material UI's DataGrid GridActionsCellItem within a custom wrapper component triggers a visual glitch if showInMenu is enabled

Here is how my MUI DataGrid columns are structured: const columns = [ { field: "name", type: "string" }, { field: "actions", type: "actions", width: 80, getActions: (params) => [ ...