The ngResource PUT method is triggering a bad request error specifically because of the presence of both $promise and $resolved in

I've been trying to solve this issue for hours now, and despite following various tutorials, I still can't get it to work.

The problem lies with my PUT request which returns a 400 (Bad Request) error:

PUT http://localhost:8083/stockapi/rest/stocks/5485cba248673a0dd82bb86f 400 (Bad Request)

Upon inspecting the request, I noticed that it includes $promise and $resolved data elements:

> {"id":"5485cba248673a0dd82bb86f","name":"iShares ESTOCK DivXXX","ticker":"AMS:IDVY","url":"https://www.google.com/finance?q=AMS%3AIDVY&ei=F5BxVLiCB8GlwQPJ1YD4DQ","currency":"EUR","currentPrice":19.81,"currentPriceInEuro":19.81,"lastModified":1418054562234,"historyStockPrices":[{"timestamp":1418054562234,"price":19.81}],"$promise":{},"$resolved":true}

This behavior seems to be linked to the ngResource object, as indicated by several tutorials suggesting that the code below should address it, but it doesn't:

Update/edit: when I send the JSON object without the "$promise" and "$resolved" elements via an external tool like Postman REST client, it works perfectly fine.

Factory:

.factory('Stock',function($resource){
return $resource('http://localhost:8083/stockapi/rest/stocks/:id',
    { id: '@id' },{
        update: { method: 'PUT' },
        show: { method: 'GET' }
    }); });

Controller (note: despite attempting 4 updates, none of them are successful - resulting in 4 Bad Requests):

.controller('StockEditController',function($scope,$log,$http,$state,$stateParams,Stock){

$scope.stock = Stock.get({id:$stateParams.id});

$scope.updateStock=function(stock) {
    Stock.update(stock);
    stock.$update();

    Stock.update($scope.stock);
    $scope.stock.$update();

    $state.go('stocks');
};

});

I'm currently at a loss regarding how to correctly utilize the ngResource object to make PUT/POST calls to my web service. Any suggestions would be greatly appreciated!

Thank you!

UPDATE: Chrome network output:

Response header

Remote Address:[::1]:8080
Request URL:http://localhost:8080/stockapi/rest/stocks/5485cba248673a0dd82bb86f
Request Method:PUT
Status Code:400 Bad Request
Request Headersview parsed
PUT /stockapi/rest/stocks/5485cba248673a0dd82bb86f HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 355
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, */*
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36
Content-Type: application/json;charset=UTF-8
Referer: http://localhost:8080/stockapi/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Request Payloadview parsed
{"id":"5485cba248673a0dd82bb86f","name":"iShares ESTOCK DivXXXYYY","ticker":"AMS:IDVY","url":"https://www.google.com/finance?q=AMS%3AIDVY&ei=F5BxVLiCB8GlwQPJ1YD4DQ","currency":"EUR","currentPrice":19.81,"currentPriceInEuro":19.81,"lastModified":1418054562234,"historyStockPrices":[{"timestamp":1418054562234,"price":19.81}],"$promise":{},"$resolved":true}
Response Headersview parsed
HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Language: en
Content-Length: 968
Date: Tue, 09 Dec 2014 06:36:24 GMT
Connection: close

Answer №1

Based on the information provided in the documentation, it appears that there is a mistake in the way you are using the update action.

Therefore, your updateStock function should be adjusted as follows:

$scope.updateStock=function(stock) {
    Stock.update({id: stock.id}, stock);

    Stock.update({id: $scope.stock.id}, $scope.stock);   //It's unclear why there are two calls here

    $state.go('stocks');
};

Answer №2

Upon reviewing the factory definition and comparing it to mine, I recommend updating the second parameter of the factory definition to an array like so:

.factory('Stock',[$resource, function($resource){
    return $resource('http://localhost:8083/stockapi/rest/stocks/:id',
        { id: '@id' },{
            update: { method: 'PUT' },
            show: { method: 'GET' }
    }); 
}]);

I am not certain if this will resolve the issue, but it does deviate quite a bit from Angular's documentation on dependency injection which can be found here: https://docs.angularjs.org/guide/di

If this doesn't solve the problem, could you also display the contents of $scope.stock after the GET request retrieves the data?

Answer №3

While this question may be old, I recently encountered a similar issue and came across this Stack Overflow post. Additionally, I found another related question that provided some helpful insight:

One user suggested that the problem could be attributed to CORS (cross-origin resource sharing) restrictions. This implies that your server-side configuration needs to permit such requests. In case you are utilizing Spring MVC, simply adding the

org.springframework.web.bind.annotation.CrossOrigin
annotation in the controller's request mapping should suffice:

@CrossOrigin
@RequestMapping(value = "/product/{id}", method = RequestMethod.POST)
@ResponseBody
public void updateProduct(@PathVariable("id") final long id, @RequestBody final ProductDto productDto) {
    // your implementation here
}

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

Using jQuery to verify if the content of the tag matches "sometext" before executing a specific action

If I have multiple instances of the following in my content div: <cite class="fn">blabla</cite> What is the best way to check each cite tag's content (e.g. blabla) with a class of fn and change its color to red if it equals "sometext"? I ...

Tips for creating a clickable popover within a window that remains open but can be closed with an outside click

Is there a way to ensure that my popover window remains clickable inside its own area without closing, but automatically closes when clicked outside of the window? This is the code I am currently using, which is triggered by a button click: if (response. ...

Utilize jQuery to showcase a chosen cryptocurrency from coinmarketcap's API

I've been attempting to retrieve specific coin data from the Coinmarketcap API using JavaScript, but for some reason, nothing seems to be working. I'm really puzzled about where I might have gone wrong... var coin = "spectrecoin"; $.get("https ...

Issues with Karma's base path functionality

I am encountering issues with launching tests using Karma for the first time. My folder structure is as follows: node_modules -angular-mocks src -compiled -lib -tests -karma.conf.js Within my karma.conf.js file, these are my file list and basepat ...

Enhance the appearance of the jQuery document.ready function

I'm attempting to customize the jQuery document.ready function <html> <head> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript> $(function() { c ...

Creating custom shaders for YouTube videos within a Three.js userscript

I want to add a shader effect to YouTube videos. My current approach involves using Three.js to implement a shader on a video. Specifically, I am trying to adapt this example of applying a shader to a video (code available here) into a Tampermonkey usersc ...

What is the best approach to structure a React project in which a component's rendering changes with each instance?

I am facing a challenge with rendering a component that relies on multiple AJAX calls to complete. These AJAX responses return different data each time, and I want to implement a button that will trigger the re-rendering of this random component every time ...

Creating new Angular2 Observables - Subscribing to undefined developments

Is it a scoping issue or a problem with how my observables are set up? Can you assist me in figuring it out? To explain my logic: My goal is to first check if the data is available locally before making an http.get request for it. I want to return the loc ...

Changing return values with Jest mocks in TypeScript

Here I am again with a very straightforward example. In summary, I require a different response from the mocked class. Below is my basic class that returns an object: class Producer { hello() { return { ...

The processing-js library threw a Reference Error indicating that the Navigator could not be found

I am looking to utilize processingJS as an npm package in a nodeJS server for deployment on MS Azure. I am using VS15 and encountering difficulties referencing it: var pjs = require('processing-js'); var http = require('http'), fs = r ...

Guide on showcasing the values from two text fields with autocomplete suggestions in a third text field

Hey there, I have a search form that takes values from two text fields and combines them to populate a third text field for querying. <form name="form1" method="post" action="" autocomplete="off" oninput="sea.value = password.value +''+ passw ...

Tips for preventing multiple button clicks until the completion of the initial click event

I created a clock that tells the time every quarter as per the professor's request. However, there is an issue - when I click multiple times, the clock keeps telling the time repeatedly until the number of tellings matches the number of clicks. I thou ...

What is the best way to set the input type file to null when deleting an image in Vue?

My form allows users to upload an image, and everything was functioning properly until I encountered an issue. When I remove an image and try to upload the same image again, the @change function is not triggered. I am unable to reset the file value to null ...

What is the process for specifying a dependency on an ng-metadata module?

I am currently working on a project that is utilizing ng-metadata for creating a few Angular 1.5 modules. One of the test modules/components in this project has the following structure: import { NgModule, Component, Inject, Input, Output, EventEmitter } f ...

Having difficulty choosing an element with protractor's virtual repeat functionality

Initially, I successfully used ng-repeat to select an element. However, the developers have since implemented virtual repeat which has caused the following code to stop working: expect(stores.listStores(0).getText()).toContain('Prahran'); expect ...

Prevent the initial delay caused by setTimeout

I am currently working on a script to incorporate floating clouds on my website. However, I am facing an issue where the first cloud appears with a delay of 10-12 seconds due to the setTimeout function in spawn_cloud_loop. Is there a way to add the first c ...

Tips for concealing the Bottom bar action in React Native

Currently facing an issue with React Native - I need to hide the bottom action bar located just below my tab bar navigation. I'm trying to create a clone of the Disney + App and this particular problem has me stuck: Here's the bottom part of my ...

Struggling to toggle the visibility of a table with a button - successfully hiding it, but unable to make it reappear?

I need a button that can toggle (show/hide) a table. Currently, my code hides the table successfully, but it fails to show the table again when I click the button. It seems like there is an issue with refreshing or redirecting after clicking the button for ...

How to efficiently await multiple promises in Javascript

My Objective: Collect artist IDs Find them in the database Create new ones if needed Create an event record in the database and obtain its ID Ensure all artist IDs and event ID are gathered before proceeding Loop through combin ...

Attempting to retrieve assets from an incorrect directory in a rush

Within my express project, I have encountered an issue when rendering the product route with a specific id. It seems that the assets are attempting to load from /products in the public folder (even though this directory does not exist). However, when I ren ...