Maximizing PUT Methods in HTTP RESTful Services

I've been playing around with my routes file and I'm looking to switch up the method being called (delete instead of update).

Code Snippets:

# User management API
GET     /users                      @controllers.Users.findUsers
POST    /user                       @controllers.Users.createUser
PUT     /user/:firstName/:lastName  @controllers.Users.updateUser ( firstName: String, lastName: String )
PUT     /user/:firstName/:lastName  @controllers.Users.deleteUser( firstName: String, lastName: String )

Additionally:

    updateUser: (firstName, lastName, user) ->
      @$log.debug "updateUser  #{angular.toJson(user,true)}"
      deferred = @$q.defer()

      @$http.put("/user/#{firstName}/#{lastName}", user)
        .success((data, status, headers) =>
            @$log.info("Successfully updated user - status #{status}")
            deferred.resolve(data)
        )

        .error((data, status, header) =>
            @$log.info("Failed to update user - status #{status}")
            deferred.reject(data)
        )
        deferred.promise


    deleteUser: (firstName, lastName, user) ->
      @$log.debug "deleteUser  #{angular.toJson(user, true)}"
      deferred = @$q.defer()

      @$http.put("/user/#{firstName}/#{lastName}", user)
        .success((data, status, headers) =>
            @$log.info("Successfully deleted user - status #{status}")
            deferred.resolve(data)
        )

      .error((data, status, header) =>
          @$log.info("Failed to delete user - status #{status}")
          deferred.reject(data)
      )
      deferred.promise

servicesModule.service('UserService', ['$log', '$http', '$q', UserService])

Is there a way to differentiate between the two PUT routes? Or specifically call a PUT route?

Answer №1

Instead of using put in the delete action, consider utilizing the DELETE http request type. Your code can be modified to look like this:

GET users
POST user
PUT user/:firstName/:lastName
DELETE  user/:firstName/:lastName

To differentiate between two similar actions, a simple solution is to adjust the route. For example:

PUT user/:firstName/:lastName
PUT user/update/:firstName/:lastName

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

Rails: The "link_to" method for logging out and deleting sessions is unresponsive

My app allows users to view blog posts once they are "signed up/ logged in" and saves their id in session[:user_id]. An issue I am facing is with the "link_to" method for logging out. When hovering over the "Logout" link in the browser, it doesn't ap ...

How can I resolve the issue of encountering the "Modal dialog present: If you navigate away from this page, any unsaved changes will be lost" message while using Internet Explorer with

Here's the code snippet I'm working with. While it successfully removes the alert box, it throws an error in the console: Exception in thread "main" org.openqa.selenium.UnhandledAlertException: Modal dialog present: If you leave this page, any c ...

Unlock the secret: Using Javascript and Protractor to uncover the elusive "hidden" style attribute

My website has a search feature that displays a warning message when invalid data, such as special characters, is used in the search. Upon loading the page, the CSS initially loads like this: <div class="searchError" id="isearchError" style="display: ...

Is it possible to directly utilize functions from an imported JavaScript library, such as Change Case, within the template of a Vue component?

After successfully importing and using the Change Case library within the <script></script> element of a Vue component, I now seek to directly utilize the Change Case functions in the template itself. As of now, my understanding is that when d ...

Organizing content into individual Div containers with the help of AngularJS

As someone who is new to the world of AngularJS, I am currently in the process of learning the basics. My goal is to organize a JSON file into 4 or 5 separate parent divs based on a value within the JSON data, and then populate these divs with the correspo ...

Utilize AjAx and the post method to transmit data to a servlet

function checkInputValue (value){ var input = value; $.ajax({ url:"ggs.erm.servlet.setup5.AjaxS", data:{ userInput :input}, success:function(){ alert("Success! Code executed successfully."); } }); } ...

Only the initial AJAX request is successful, while subsequent requests fail to execute

I am facing an issue with multiple inputs, each requiring a separate AJAX request. < script type = "text/javascript" > $(document).ready(function() { $("#id_1").change(function() { var rating1 = $(this).v ...

Updating model values while dragging with Angular Dragular

Currently, I am experimenting with dragula and its newer version, dragular, on some sample projects. One specific dilemma I am facing involves the implementation of drag and drop functionality in an Angular project. My query pertains to utilizing a list o ...

Tips on capturing the response data in UI testing automation

Currently, I am working on automating a login page using WebDriverIO for UI Automation. After clicking the Login button, a request to *.com/user/login is triggered in the background. I need to capture this call's response in order to obtain a token r ...

The special function fails to execute within an "if" condition

As a newcomer to JavaScript/jQuery and Stack Overflow, I kindly ask for your patience in case there are any major errors in my approach. I am currently developing an HTML page with Bootstrap 3.3.7, featuring a pagination button group that toggles the visib ...

Is it possible for a prop to change dynamically?

I am currently developing a component that is responsible for receiving data through a prop, making modifications to that data, and then emitting it back to the parent (as well as watching for changes). Is it possible for a prop to be reactive? If not, wh ...

The Bootstrap Navbar appears hidden beneath other elements on mobile devices

While using bootstrap to style my header contents, I encountered a strange issue. The navbar that appears after clicking on the hamburger menu is displaying behind all the components. Even though I've set the z-index to the maximum value, it still doe ...

Is there a CSS3 Selector With Similar Functionality to jQuery's .click()?

For a few years now, I have been utilizing a pure CSS navigation system. However, with the recent increase in mobile site projects at my workplace, I am encountering issues with drop-down menus not functioning properly on mobile devices. Despite this chall ...

Unexpected behavior: JQuery Ajax request not displaying Json object following recent update to JQuery version 1.10.2

Currently facing an issue with a project I am working on. The previous programmer used jquery 1.4.4, and I have updated it to 1.10.2 due to the designer using Bootstrap. However, after running it in version 1.10.2, one of the objects that was functional i ...

Including a label for an array within an unnamed array in a JSON string

Is there a way to transform the following data: [{"name": "Donald"}, {"name": "George"}] Into this format instead: {MyArray: [{"name": "Donald"}, {"name": "George"}]} I am currently working on a database server that I built using node.js, express, an ...

How can I arrange selected options at the top in MUI autocomplete?

I am currently working with mui's useAutocomplete hook https://mui.com/material-ui/react-autocomplete/#useautocomplete Is there a way to programmatically sort options and place the selected option at the top using JavaScript sorting, without resorti ...

How can I use JavaScript to find a keyword on a webpage that is not located within an <a> tag or its href attribute?

I'm on a mission to locate a specific keyword within a webpage. Sounds simple, right? Well, here's the tricky part - I need to disregard any instances of this keyword that are nested within an <a> tag. For example: <p>Here is some s ...

VueJs has the ability to display/render a single object from a collection of hundreds of objects at a time

When my API returns hundreds of objects in a response, I want to display only one object at a time on a page. The page includes two buttons - Previous and Next - that allow users to navigate between objects. How can I efficiently manage this data retriev ...

Recover information from an angular directive

I have developed a unique directive named my-tree, and I am utilizing this directive in a view named example-tree-view.html as illustrated below: <my-tree ng-model="sampleTreeView.listNodes" ... /> The controller for this view is called sampleTreeV ...

Transfer data via ajax to the controller

I need assistance with storing a file in my database using Tabulator without having a form already created. I am currently creating a simple input element like this: var editor = document.createElement("input");. After clicking the file, it trigg ...