Struggling with a 400 Bad Request Error in Angular with WebAPI Integration

I've been working on creating a database to keep track of comics, and so far I can successfully add new comics and retrieve them using GET requests. However, I've hit a roadblock when trying to update existing comics using PUT requests. Every time I attempt to update, I receive a bad request error, even though I believe all the information is correct. I've double-checked everything, but I can't seem to figure out what the issue is.

My main goal is to enhance the comic list so users can manage both their physical and digital comic copies.

Thank you in advance for any help.

Below is my DBController.cs:

 [Authorize]
    public IHttpActionResult Put(Comic comic)
    {
        string UserId = User.Identity.GetUserId();
        if (UserId == null) return BadRequest("You Must Be Logged In to Edit");

        else if (comic.UserId == UserId || User.IsInRole("Admin"))
        {

            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                var currentComic = db.Comics.Find(comic.ComicId);
                currentComic.IsDigital = comic.IsDigital;
                currentComic.IsPhysical = comic.IsPhysical;
                db.SaveChanges();
            }
            return Ok();
        }

        else return BadRequest("Insufficient privileges");
    }
}

Furthermore, here is my CollectionController.js:

$scope.physical = false;
$scope.digital = false;

$scope.updateComic = function (ComicId) {
        var comic = {
            ComicId: ComicId,
            IsPhysical: $scope.physical,
            IsDigital: $scope.digital,
            }
 return MarvelApiFactory.editComic(comic).then(function (data) {
        })
}

In addition, my ApiFactory.js:

 var editComic = function (comic) {

          var deferred = $q.defer();

          $http({
              url: '/api/ComicDB',
              method: "PUT",
              headers: { Authorization: "Bearer " + localStorage.getItem('token') },
              data: comic
          }).success(function () {
              deferred.resolve();
          }).error(function () {
              deferred.reject();
          })
          return deferred.promise;
      }



return {
        editComic: editComic,
    }

Moreover, here is my .html:

<button class="btn btn-danger"  ng-click="updateComic(x.ComicId)">Save</button>

Finally, the error messages I'm receiving. I'm not entirely sure what information you need, but last night I was able to find inner exceptions and more details in the network tab. However, this time I'm unable to locate them or I might not be receiving any. The JS console shows the following error:

PUT http://localhost:53612/api/ComicDB 400 (Bad Request)angular.js:9827 (anonymous function)angular.js:9628 sendReqangular.js:9344 serverRequestangular.js:13189 processQueueangular.js:13205 (anonymous function)angular.js:14401 Scope.$evalangular.js:14217 Scope.$digestangular.js:14506 Scope.$applyangular.js:21440 (anonymous function)jquery-1.10.2.js:5109 jQuery.event.dispatchjquery-1.10.2.js:4780 elemData.handle

Answer №1

By default, IIS Express and IIS8 do not have PUT and DELETE enabled. However, you can activate these methods by following these simple steps:

  1. Begin by opening the applicationHost.config file on the machine where the Web Api application is hosted. You can find this file at %userprofile%\documents\IIS{Express|8}\config”.

  2. Next, navigate to the end of the IIS applicationHost.config file and locate a handler entry that begins with:

    <add name="ExtensionlessUrl-Integrated-4.0"...`. 
    
  3. Within the "verb" attribute, append PUT and DELETE so that the "verb" attribute reads as follows: verb="GET,HEAD,POST,DEBUG,PUT,DELETE"

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

Retrieving JSON information using Angular.js

I have been struggling to fetch JSON data from a URL using the code provided below. Unfortunately, it seems that the data is not being populated as expected. Despite trying various approaches, nothing seems to work out successfully. Below is the basic code ...

What could be causing the issue with the $http.delete method in AngularJS?

When trying to use $http.delete with Django, I encountered an HTTP 403 error. Here is my JS file: var myApp = angular.module('myApp',['ui.bootstrap']); myApp.run(function($http) { $http.defaults.headers.post['X-CSR ...

Differences between using "break + return" and simply "return" in

Currently, I am developing a nodejs Heap and ensuring top performance is key. The code snippet I have looks like this: while(true) if(x) do something return if(y) do ... return if(z) do ... else return Suggestions were made to me to incorporate ...

Troubleshooting: jQuery toggle() issue in Firefox 3.0.12

My jQuery code for toggling is working perfectly in IE6 but not in FF3. I'm wondering what could be causing this issue and if there is a workaround available. <button>Toggle Me</button> <p>Hi</p> <p>Learning jQuery&l ...

Using HTML and CSS to capture user input data and store it in an array

I've created a form that allows users to add and remove multiple fields, ranging from one to three. My goal is to retrieve the form data and store it in an array. index.html <!DOCTYPE html> <html lang="en"> <head> ...

React - Error: you have a syntax problem because there is an unexpected token <

I am working on a project using Express, pg, and react. However, I have encountered some issues with React. Here is the directory of my project index.js var express = require('express'); var server = express(); var path = require('path&ap ...

Trouble with the div element's change event

Hey there! I'm having trouble with this jQuery code that is supposed to fade in or fade out a div based on its contents. Here is the HTML code: <div class="mainContentWrapper"> sample text </div> And here is the CSS code: div.main ...

Employing buffers and streams for data transmission

I am in need of a node.js program that can effectively handle a large JSON dataset with thousands of records. Specifically, I require a script that can extract only the "name" key from each record and transfer it to another file using streams. If there ar ...

Accessing form data within Mongoose schema hooks via JavaScript

I have a form where I've split the content into two separate MongoDB schemas. I want to access variables that are within node.js/express.js directly in mongoose schema hooks, whether through pre or post hooks of the schema. Here are my files: expres ...

AngularJS and Bootstrap carousel combined for a dynamic multi-item per slide display

Currently, I am utilizing Bootstrap to showcase a carousel on my website, where multiple items are displayed per slide as demonstrated in this example. The use of static images has yielded satisfactory results, as evidenced by the jsFiddle example found he ...

Using Database Data in a Material UI Select Component

I'm having trouble populating a select component from Material UI with data retrieved from my database. Although I can display the data in the component, upon selecting an option it breaks and displays the error "categorias.map is not a function". Any ...

Ways to extract text from a temporary element

Here is my HTML code: <div class="p-login-info" ng-show="loggedOut()">My text.</div> This is the corresponding JavaScript code: var e = element(by.className('p-login-info')); e.getText() .then(function(text){ var logoutText = ...

Using an action code to retrieve the current user from firebase: A step-by-step guide

I am in the process of designing 2 registration pages for users. The initial page prompts the user to input their email address only. After they submit this information, the following code is executed: await createUserWithEmailAndPassword(auth, email.value ...

Issue encountered when assigning a new value to a private class property at a global scope in JavaScript

I am encountering an issue in my code where I define a private class member using "#", initialize it in the constructor, and then receive an error when attempting to set/access the value. Uncaught TypeError: Cannot read private member #mouse from an object ...

ajaxform is not providing the correct response

There is a form below that logs into Instagram based on the response it receives. If the login is successful (returns "ok"), then it shows success, otherwise it should display an error state. However, in my case, it always returns a null state for some un ...

Dynamic updating of scores using Ajax from user input

My goal is to design a form that includes three "Likert Scale" input fields. Each of these three inputs will have a total of 10 points that can be distributed among them. The submit button should become enabled when the score reaches 0, allowing users to s ...

Obtaining values from event listeners in Vue.js across different methods

Looking for guidance on the code snippet provided below. Is there a way to assign the value of "e.detail.name" to "nodeName," and then access it in a different method within the component for an API request? data() { return { nodeName: '' ...

Create a function in JavaScript that can generate a random number a specified number of times based on user input

I have been struggling to develop a JavaScript program that can generate a random number multiple times based on user input. Despite numerous attempts, I haven't been able to get it to work. Below is the code snippet I've been working with: f ...

Incorporating a dynamic HTML editing button to every new row in a table using JavaScript

My application features a form that allows users to dynamically add new rows to a table using JavaScript: // Function to add a new account row if (tit.innerHTML === "Add Account"){ var table = document.getElementById(tableId); var row = table ...

Displaying items using a filter function in ng-repeat

I am facing an issue with using a filter on my ng-repeat that involves a function with a parameter passed in, but for some reason, the filter is not working as expected. The function I am using for the filter compares two arrays to find any matching eleme ...