405 - Sorry, this method is not allowed for deletion

The issue at hand involves a Spring RESTful web service and a client. When attempting a DELETE request on the server, the following error is encountered: ->

DELETE http://localhost:8080/employee/3/logout 405 (Method Not Allowed)

Despite implementing the CORS filter, the problem persists.

EmployeeCotroller

@Controller
@RequestMapping(value = "/employee")
public class EmployeeController {
    private static final EmployeeRepository employeeRepository = new EmployeeRepository();
public EmployeeController(){
}

@RequestMapping(method = RequestMethod.GET, value = "/{employeeId}")
public ResponseEntity<EmployeeDTO> showEmployeeById(@PathVariable int employeeId)
{
    employeeRepository.setEmployeeAsActive(employeeId);
    EmployeeDTO employeeDTO = employeeRepository.getEmployeeDTOForId(employeeId);
    if(employeeDTO != null)
    {
        return new ResponseEntity<EmployeeDTO>(employeeDTO,HttpStatus.OK);
    }
    return new ResponseEntity<EmployeeDTO>(employeeDTO,HttpStatus.NOT_FOUND);
}

@RequestMapping(method = RequestMethod.GET, value = "/{employeeId}/viewTasks")
public ResponseEntity<List<TaskDTO>> showTasksForEmployeeId(@PathVariable int employeeId)
{
    List<TaskDTO> taskDTOs = employeeRepository.getTasksForEmployee(employeeId);
    if(taskDTOs != null)
    {
        return new ResponseEntity<List<TaskDTO>>(taskDTOs, HttpStatus.OK);
    }
    return new ResponseEntity<List<TaskDTO>>(taskDTOs, HttpStatus.NOT_FOUND);
}

@RequestMapping(method = RequestMethod.DELETE, value = "/{employeeId}/logout}")
public ResponseEntity<Void> logoutEmployeeById(@PathVariable int employeeId)
{
    employeeRepository.logoutEmployeeById(employeeId);
    return new ResponseEntity<Void>(HttpStatus.OK);
}

}

The location where the request is made:

var url = "http://localhost:8080/employee/" + document.cookie1;
$('#employeeLogout').click(function(){
        $.ajax({
           type: "DELETE",
            url: url + "/logout",
            async: true
        });
        document.cookie1 = null;
        window.location.assign('http://localhost:9000/#/employees');
    });

And here's my CORS filter

    @Component
public class CORSFilter implements Filter {
    //Web container will call a filter when the request was made.
    // CORS filter allows Cross-Origin requests-responses to be performed by adding Access-Controll-Allow-Origin in the header"
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}
}

Answer №1

I am facing a similar issue and finding it challenging to resolve. It seems like the issue lies within the setup of Spring Security, as my code functions properly without any security measures in place. However, once I enable Spring Security, only the GET method is permitted, while PUT, POST, and DELETE methods are restricted.

Answer №2

After investigating further, I discovered that the issue stemmed from the server-side mappings. The server was expecting the username, but I was sending the name instead. It turned out to be a simple oversight on my part :). Remember, when encountering unexpected errors, always double-check for simple mistakes!

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

Utilizing a JavaScript-sent URL within a PHP data grid: A step-by-step guide

I am working on a JavaScript function that fetches the URL of an API needed for a data grid. This API displays the students assigned to a particular teacher. The data grid must dynamically change based on the user (the teacher initiating the session), and ...

Having trouble accessing information from Firebase Realtime Database within a React Native application

I am currently developing a React Native application that interacts with a Firebase database for reading and writing data. I have configured my Firebase permissions to allow read and write access: { "rules": { ".read": true, ...

Using Jquery to loop through a function for every select box that is added dynamically

Encountering some challenges with jQuery while attempting to utilize the same function and iterate over select boxes that are dynamically generated with jQuery's clone() method. Here is a snippet of the content being cloned: <select name="expense ...

How can you extract path information from an SVG file and utilize it as a marker on Google Maps?

I want to implement a custom SVG icon as a marker on Google Maps. I have obtained this SVG file: <svg xmlns="http://www.w3.org/2000/svg" width="510px" height="510px" viewBox="0 0 510 510"> <g stroke="black" stroke-width="10" ...

Transitioning from left to right, picture smoothly scrolls into view using Way

I've explored various websites and even attempted to decipher a waypoint guide, but unfortunately, I haven't had any success. The scroll function doesn't seem to be working with the code below. (source: ) Any assistance on this matter would ...

Transforming the data retrieved from the API into a well-organized object in Vue.js

Currently, I am utilizing the vue-meta library to incorporate meta tags into my Vue project. What I'm attempting to do now is populate my meta tags using the API response data. Here's an example output from the API when I log 'response.data. ...

How can we split the state between unique React forms that are interconnected?

My issue is that, based on the value of a prop in my form (specifically step), I need to display different forms. Everything works fine; the form loads the text programmatically as needed and fills in the form accordingly. However, when the value of step c ...

The issue arises when d3.scaleLinear returns NaN upon the second invocation

My journey with d3.js is just beginning and I'm taking it slow. Currently, I'm focused on creating a bar chart where data is loaded from a json file. When I click on the bars, the data changes to another column in the json. This is how my json f ...

Rotating the camera around the origin in Three.js

Hey, I'm having some trouble with what I thought would be a simple task. I have a group of objects at the origin, and I'm trying to rotate a camera around them while always facing the origin. According to the documentation, this code should work: ...

Enhance cross-browser compatibility with JQuery updates

I've successfully implemented a private chat system, but I'm facing an issue with the visibility of the chat boxes. Currently, they are not visible by default. When a user clicks on a name to start chatting, I'm using jQuery to show the chat ...

How to retrieve response cookies using RxJS Ajax

When using RxJS to make an Ajax call request, I am able to set the headers of the request. However, I am wondering how I can retrieve the Cookie from the RxJS Ajax Response? import { ajax } from 'rxjs/ajax'; ajax({ url: "some url", body: ...

What methods are typically used for testing functions that return HTTP observables?

My TypeScript project needs to be deployed as a JS NPM package, and it includes http requests using rxjs ajax functions. I now want to write tests for these methods. One of the methods in question looks like this (simplified!): getAllUsers(): Observable& ...

What could be the reason that the painting application is not functioning properly on mobile devices?

I am facing an issue with my painting app where it works perfectly on desktop browsers but fails to function on mobile devices. I tried adding event listeners for mobile events, which are understood by mobile devices, but unfortunately, that did not solve ...

Tips for implementing validation in JavaScript

I'm brand new to learning Javascript. Recently, I created a template for a login page and it's working perfectly fine. However, I am struggling with setting up validation and navigation. My goal is to redirect the user to another page if their us ...

Implementing pagination in a table with the help of jQuery

I've been working on this code for the past few days and I'm struggling to find a solution that meets my requirements. What I need is pagination within a specific section of a table, with the following actions/events: When clicking previous o ...

How can I ensure that the size of the Dropdown Menu Item matches its parent in both Bootstrap and CSS styles?

I am working on a navigation bar that has a dropdown menu which appears on hover. I want the size of the dropdown menu items to match the size of the parent element. Here is an image for reference: https://i.stack.imgur.com/oNGmZ.png Currently, the "One ...

Implementing server authentication with Faye in Node.js

As a complete newbie to node.js and faye, I'm struggling with the basics and not sure what questions to ask. This is how my faye server setup looks like, running on Nodejitsu: var http = require('http'), faye = require('faye' ...

We encountered an error: The function setName is not defined

I am working on some code where I have defined a function, but it is still showing me errors related to setname, setemail, and password. import React, {useState} from 'react' import './Auth.css' import icon from '../../assets/logo. ...

Vertical alignment of content over image is not in sync

I am attempting to center my div container .home-img-text vertically in the middle of its parent div .home-img. Despite trying various methods such as setting .home-img-text to position: absolute, relative, adding padding-top, and several others, I haven&a ...

Issues with debuggers in Chrome and Firefox with AngularJS are causing frustration for developers

Currently, I am in the process of developing a hybrid application that combines AngularJS with Angular 8. As part of my testing procedure, I am attempting to debug the application. However, I have encountered an issue where the debuggers function properly ...