`Using asp net core leads to a Fetch: TypeError issue``

I have been working on an application using asp net core with Razor Pages. I spent a lot of time trying to figure out how to process POST requests (specifically OnPost in razor pages). After reading through the documentation at "https://learn.microsoft.com/ru-ru/aspnet/core/security/anti-request-forgery?view=aspnetcore-8.0", I decided to add a secure token for JavaScript and started processing POST requests. However, now I am getting a Fetch: TypeError error in response from the server. It seems like I'm missing something important, but I can't quite figure out what it is. When I start processing the request with "app.Map", everything works fine without any issues.

Issue 1: Firefox shows - Content-Length header of network response exceeds response Body. How can I resolve this issue in my code?

Issue 2: It's interesting that the headers are the same and do not contain a Content-Length when I use app.Map it works fine, but if I use a razor page, I encounter an exception.

Headers: { "content-type" - "application/json; charset=utf-8", date - "Mon, 08 Jul 2024 04:22:46 GMT", server - "Kestrel", "x-firefox-spdy" - "h2" }

This is part of my working code:

app.Map("/FormResult/GetRes", HandleMapFormRes);

static void HandleMapFormRes(IApplicationBuilder app)
{
    string text = string.Empty;
    app.Run(async context =>
    {

        if (context.Request.Method == "POST")
        {
            try
            {
             /* .......
              .......
              .......
              ....... */

                JsonFormToClient jsonFormToClient = new JsonFormToClient();
                jsonFormToClient.Blockinfo = results;
                jsonFormToClient.CountOfBlocks = c;
                string ResponceJson = JsonConvert.SerializeObject(jsonFormToClient);

                await context.Response.WriteAsJsonAsync(ResponceJson);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

    });
}
function drawChart(pathToPage,token) {
    var htmlContent = pathToPage;
    var formData = new FormData();
    formData.append('htmlContent', htmlContent);
    fetch(pathToPage, {
        method: 'POST',
        body: formData,
        headers: {
            "X-XSRF-TOKEN": token
        },
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            var a = response.json();
            return a;
        })
        .then(jsonData => {
            a = JSON.parse(jsonData);

            for (let i = 0; i < a.CountOfBlocks; i++) {
                AddNewBlock(a.Blockinfo[i].Id_in_html);
                drawnow(a.Blockinfo[i]);
            }
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
}

If I process this with Razor Page (OnPost), the response will break

Answer №1

The solution to my query would be to utilize:

string JSONResponse = JsonConvert.SerializeObject(formData);
return new JsonResult(JSONResponse);

////await Response.WriteAsJsonAsync(ResponceJson); doesn't work

Answer №2

When sending a POST request to the same URL (pathToPage) that you are trying to fetch, using the get function to post to the same page is not a common practice. Typically, an API endpoint would handle a POST request.

Furthermore, reusing and redeclaring the Variable a can lead to confusion and errors.

You can attempt the following approach:

function drawChart(pathToPage, token) {

  var htmlContent = document.documentElement.innerHTML; 
  var formData = new FormData();
  formData.append('htmlContent', htmlContent);

  fetch(pathToPage, {
      method: 'POST',
      body: formData,
      headers: {
          "X-XSRF-TOKEN": token
      },
  })
  .then(response => {
      if (!response.ok) {
          throw new Error('Network response was not ok');
      }
      return response.json(); 
  })
  .then(jsonData => {
      for (let i = 0; i < jsonData.CountOfBlocks; i++) {
          AddNewBlock(jsonData.Blockinfo[i].Id_in_html);
          drawnow(jsonData.Blockinfo[i]);
      }
  })
  .catch(error => {
      console.error('Error fetching data:', error);
  });
} 

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

Change the height of textarea dynamically using jQuery

I am trying to create a comment box similar to Facebook's, where it resizes as text fills it using Expanding Text Areas Made Elegant This is how my view looks: <div class='expandingArea'> <pre><span></span></ ...

Understanding the process of configuring Quasar Language in SSR Mode using route parameters

Is there a way to incorporate Quasar Language Packs while utilizing this specific routing method and SSR mode? const routes = [ { path: '/:locale?', beforeEnter: localeNavGuard, children: [ ... ] } ] ...

"Can you direct me to the location where I can access .NET source code for

Is there a reliable source where I can access the source code for the .NET Framework, specifically libraries? I am looking for the source code for reflection methods such as invoke and others. ...

Issue: React child must be a valid object - Runtime Error Detected

As I delve into the world of React, NextJs, and TypeScript, I stumbled upon a tutorial on creating a navbar inspired by the 'Strip' style menu. It has been quite a learning journey for me as a newbie in these technologies. After seeking help for ...

"Encountering an issue with logging in the Node.js application on Heroku. Error

As a beginner on Heroku, I am facing an application error when trying to run my node.js app for the first time. I am having difficulty identifying the issue as the program works perfectly locally. Below is the log. If necessary, I can provide the node.js c ...

Retrieving external JSON data with JavaScript

I am attempting to utilize a specific service for proxy checking. They offer an uncomplicated API that delivers JSON data. My goal is to retrieve this JSON on my own server. Despite various attempts, I consistently encounter either a CORS request issue or ...

Finding a way to extract a singular text node after the Span element but before the br tag using Selenium WebDriver

I am trying to retrieve the text between span and br tags. In the HTML snippet below, I am aiming to extract the Orange text: <td role="grid cell"> <span class="ui-column-title">Fruits</span> <span id="all fruits"> "Orange" < ...

What causes the page loading issue in Firefox when a cache manifest is used?

I recently created an HTML5 game that I wanted to make playable offline. To achieve this, I added a manifest file to the game directory. The game is located in a subdirectory at /games/game/, and the manifest file resides within that same directory at /ga ...

Unable to change the value of a variable in a function in AngularJS

Calling all developers for assistance! I am experiencing an issue with updating a value dynamically inside an AngularJS controller that is being passed to an HTML tag. Everything works perfectly when updating the value outside of a function: var app = angu ...

Is it possible to include choices in the number option for slash commands in discord.js v13?

I am currently working on creating a custom slash command that includes a numerical option. Utilizing the .addNumberOption() method for this purpose. Is there a method to restrict users from inputting numbers outside the range of 0-5 after entering the Di ...

Troubleshooting Issues with AngularJS HTTP.get Requests

I'm currently working on a simple AngularJS application that is supposed to extract data from a .json file. While my code doesn't show any errors upon running it, it fails to retrieve the JSON values as expected. I have a feeling that I may be ov ...

Leverage the values of object properties from a pair of JavaScript arrays containing objects

I am working with two arrays let arr1 = [{'id': 'ee', 'seat': '12'}, {'id': 'aa', 'seat': '8'} ] let arr2 = [ {'id': 's22', 'num': '&ap ...

JavaScript table supported by a REST API

Issue at hand: I am in search of a table component that seamlessly integrates with my web application. The challenge lies in connecting the existing REST endpoints to the table for data retrieval, whether it be paginated or not. Adjusting the endpoints t ...

Unable to click on options field for selection

My collection consists of various countries const countries = [{ name: 'United States', value: 'US', currency: 'USD' }, { name: 'Israle', value: 'IL', currency: 'ILS' }, { name: 'Unit ...

Locate the latest SFTP file with a specific filename using the capabilities of SSH.NET

On an SFTP server, there is a folder containing multiple files that are generated every 60 minutes. These files have unique date and time stamps and remain in the folder for a period of 3 days. FilesCodes_Critical.2022-03-17_11-16-22-614.json FilesCodes_Cr ...

Managing AJAX Post Request Callbacks in Jasmine Testing Unit

I've been struggling to set up this test for quite a while now... it's really puzzling why it's not functioning properly. Here is a snippet of my Angular app: <body ng-app="testApp"> <div class="container" droppable> <di ...

Preserve HTML client control values during page reloads

Is there a more efficient way to retain client-side HTML controls on postback? I've attempted using enableviewstate="true", but it didn't work. My current workaround involves creating a server-side function that resets all posted values using Cli ...

Trouble arises with assembly createinstance function when integrating Crystal Report

When loading an assembly private System.Reflection.Assembly; object myData; myAssembly = System.Reflection.Assembly.LoadFile("C:\\CrystalDecisions.CrystalReports.Engine.dll"); I then proceed to create an instance. myData=myAssembly.CreateInst ...

How can we effectively utilize LESS variables in styles.less when working with LESS files within components in Angular versions 6 or 7?

Running Angular version 7.0.0 will generate a folder structure typical for "ng new". Below is the content of my styles.less file: @personal-black: #0000; This snippet shows the content of my app.component.less file: ...

Side-bar Grid React

I'm currently working on a React project and I'm struggling to create a CSS grid layout that keeps the "side panel" visible at all times. Being new to React, I find myself a bit confused when it comes to properly stacking elements. Here is the c ...