What could be the reason for the empty response in my PATCH request in Javascript?

I am facing an issue with my app that runs Rails in the backend and Javascript in the frontend. The controllers, routes, and CORS are all set up correctly. Both my Post and Get requests work without any problems. However, when I attempt to make a patch request, it successfully patches the data but returns an empty string when I use response.text(). When trying to parse it using response.json(), I encounter an error:

Uncaught (in promise) SyntaxError: Unexpected end of JSON input at game.js:25
. I need assistance in identifying the root cause of this problem.

static patchGame() {
        const numberOfClicks = parseInt(document.getElementById('click-number').textContent, 10)
        const score = parseInt(document.getElementById('score').textContent,10)
        const gameID = document.getElementById('gameID').value
        const gameObj = {game: {click_number: numberOfClicks, score: score}}
        const options = {
            method: "PATCH",
            headers: {"Content-Type": "application/json",
                      "Accept": "application/json"},
            body: JSON.stringify(gameObj)
        }
            fetch(`http://localhost:3000/games/${gameID}`, options).then(resp => {debugger}).then(game => { debugger }) // NEVER HITS last debugger    
    }

Below are the values from the resp debugger:

>resp

<-Response {type: "cors", url: "http://localhost:3000/games/28", redirected: false, status: 204, ok: true, …}
body: ReadableStream
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 204
statusText: "No Content"
type: "cors"
url: "http://localhost:3000/games/28"
__proto__: Response



>resp.text()

<-Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "pending"
[[PromiseResult]]: undefined


>resp.json()

<-Promise {<rejected>: TypeError: Failed to execute 'json' on 'Response': body stream already read
    at eval (eval at <a…}
__proto__: Promise
[[PromiseState]]: "rejected"
[[PromiseResult]]: TypeError: Failed to execute 'json' on 'Response': body stream already read at eval (eval at <anonymous> (file:///Users/muratogulcansahin/Desktop/DanceMemory/frontend/game.js:1:1), <anonymous>:1:6) at file:///Users/muratogulcansahin/Desktop/DanceMemory/frontend/game.js:24:84
message: "Failed to execute 'json' on 'Response': body stream already read"
stack: "TypeError: Failed to execute 'json' on 'Response': body stream already read\n    at eval (eval at <anonymous> (file:///Users/muratogulcansahin/Desktop/DanceMemory/frontend/game.js:1:1), <anonymous>:1:6)\n    at file:///Users/muratogulcansahin/Desktop/DanceMemory/frontend/game.js:24:84"
__proto__: Error



>resp.body

<-ReadableStream {locked: true}
locked: true
__proto__: ReadableStream

Answer №1

It appears that the response is a code 204, as anticipated for a successful PATCH request. This means no content is being sent back from the server, which could be causing the issues you are experiencing.

In this case, it would not be valid to use .text() or .json() on the missing content.

In general, PUT and PATCH requests should not return data. While a 200 response is fine, a 204 response is more appropriate in my opinion.

Answer №2

PLEASE NOTE: Upon reevaluating the question, I realized that my initial response was based solely on debugger values without fully comprehending the underlying issue. The correct answer can be found here: . I am keeping this response unchanged in case others encounter a similar problem.

ORIGINAL RESPONSE:

The error lies outside the provided code snippet.

This error typically arises from multiple calls to `.json()` within the same `fetch` chain, usually inside the second `.then()`. Make sure to only invoke `.json()` once per request, as it consumes the response body data upon execution.

To prevent this issue, monitor the `bodyUsed` property of the response object, which indicates whether the body has been consumed or not.

The following breakdown is derived from your debugger logs:

>resp
<-Response {type: "cors", url: "http://localhost:3000/games/28", redirected:
// displays the server response data (where resp.bodyUsed returns *false*)


>resp.text()
<-Promise {<pending>}
// presents the server response data as *text*, and subsequently *consumes* the body (resulting in resp.bodyUsed being *true*)


>resp.json()
<-Promise {<rejected>: TypeError: Failed to execute 'json' on 'Response': body
// fails to display the server response data due to prior consumption using `.text()`

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

Can Backbone be used to retrieve a local JSON file?

I have a simple and validated local JSON file that I am trying to fetch using Backbone.js. Here is the snippet of Backbone.js code: MyModel = Backbone.Model.extend({ defaults:{ name: '', age: 0 } }); MyCollection =Backbo ...

Aligning dynamically-sized TextInput in React Native

I am facing a challenge in centering a text input with a width that matches the length of the input text. I have tried using alignSelf: 'center' and alignItems: 'center', but the text input is not visible without specifying a width. Fo ...

Send information using AJAX's POST method

Can an image file be uploaded using the jQuery ajax post method? Will it work if the file data is simply placed in the POST request's 'data' parameter? I am working with the django framework and this is my initial attempt: $('#edit_us ...

A guide to extracting attribute values from HTML using Angular 4

I am currently working on an Angular 4 project where I needed to implement drag and drop functionality. To achieve this, I utilized the ng2-dragula plugin. Now, I have a new requirement which involves extracting the data-id attribute from each row after it ...

I am working on implementing a UPS label generation system

I am encountering an issue while trying to implement label generation using UPSP, and I keep receiving the following error message: **API Authorization failure. DelivConfirmCertifyV3.0Request is not a valid API name for this protocol.** Interestingly, wh ...

Updating the state of an array containing objects within an array of objects in React

I have a state called invoices, which is an array of objects structured like this: const [invoices, setInvoices] = useState([ { id: 123, tag_number: "", item_amounts: [ { item: "processing", amount: 159 }, { i ...

Unable to successfully download npm packages - encountered an error running `[email protected] install: `node-pre-gyp install --fallback-to-build` on Ubuntu 18.04 system

I am facing an issue while trying to npm install (using lerna bootstrap) a project on Ubuntu 18.04. The error I encounter is related to node-pre-gyp install --fallback-to-build. I have attempted installing node-gyp, node-pre-gyp, and apt-get build-essenti ...

By setting the content_type to 'application/json' in Django HttpResponse, the response will render JSON data

Attempting to implement an ajax call using jquery to a Django view. The view interacts with an external API and then sends back the result. Trying to receive the data and handle it within the success callback of the ajax call, but instead receiving a rende ...

angularslideables retro animation

I'm currently using the AngularSlideables library to toggle a modal within my Ionic project. You can check out a functional example in this fiddle: http://jsfiddle.net/3sVz8/19/ However, I am facing an issue where the initial height is set to 100% i ...

Dealing with errors in AngularJS factory servicesTips for managing errors that occur

Factory code app.factory('abcFactory', function ($http, Config, $log) { var serviceURL = Config.baseURL + '/results'; return{ results:function() { var promise = $http({ method: 'GET&apos ...

Generating a tag filter using elements from a collection of profiles

I have an array of profiles containing various skills. Each profile has its own set of tags to describe their skills. For example: profiles = [ { name: "John", skills: ["react", "javascript"]}, { name: "Jane", skil ...

Assist with JavaScript Programming

Can someone assist me in creating functionality for the "Show Picture" button to toggle the visibility of the picture when clicked? I've been trying to achieve this using an If/Else statement for a school project but have been struggling with it. Any ...

A step-by-step guide to showing images in React using a JSON URL array

I successfully transformed a JSON endpoint into a JavaScript array and have iterated through it to extract the required key values. While most of them are text values, one of them is an image that only displays the URL link. I attempted to iterate through ...

Error: The module you are trying to import from the package is not found. Please check the package path and make sure that

I encountered an issue when trying to compile a code in Reactjs. As a beginner in Reactjs, I'm struggling with this. Module not found: Error: Package path ./cjs/react.development is not exported from package /Users/mansi/letsgrowmore/to-do-list/my-rea ...

The form submission is failing due to a specific AJAX condition not being met

On my form submission page, I am trying to call a function at the time of form submission, including an AJAX request. The form submission should occur or not based on a condition in the AJAX response message. The AJAX message can have two values: 1 and 0, ...

Reading a JSON file using Javascript (JQuery)

Struggling to figure out how to handle a JSON file using JavaScript. Here are the details : { "streetCity": { "132":"Abergement-Clemenciat", "133":"Abergement-de-Varey", "134":"Amareins" } } I am attempting to access ...

Client-side filtering of jqGrid with multiple conditions

I am faced with a challenge in filtering records in a jqGrid based on multiple conditions. For example, if there are columns for Name, Age, and City, and I need to filter the grid using the following condition: Name = "Mark" and Age = 25 and City = &apos ...

Managing the ERR_NAME_NOT_RESOLVED issue

Currently, I am facing a task related to the health check endpoint where I need to receive a response from the backend or encounter a net::ERR_NAME_NOT_RESOLVED error if we are outside of a specific network. When attempting to send a request to my endpoin ...

Linking JavaScript on the client side to a NodeJS application on the server side

I am new to NodeJS and I am currently exploring the app structure. I have developed a basic app using Socket.IO and MongoJS, which functions as a tracking system that gathers variables from a client-side script and stores them in Mongo. This is how I envi ...

The first three AJAX requests are successful, but the fourth one fails to reach the PHP script

I am currently working on cascaded selects (a total of 4) that retrieve data from a database. To populate them, I use SQL queries based on the selection made in the previous select element. To establish communication between the select element and the subs ...