javascriptc#asp.net-corerazor-pages

asp net core causes an error Fetch: TypeError


I am writing an application on asp net core with Razor Pages. I to long think about how process POST requests (OnPost in razor pages), after reading this page "https://learn.microsoft.com/ru-ru/aspnet/core/security/anti-request-forgery?view=aspnetcore-8.0", I add secure token for js, and I start process POST requests, but now response from server causes an error Fetch: TypeError. I think I miss something important, but cannot understand what. If I start processing request with "app.Map", all works good without a problem.

UDP1: FireFox write - Content-Length header of network response exceeds response Body. How I can fix it in my code?

UDP2: Interesting, that headers is same, and not contains a Content-Length, if I use app.Map it work, but if I use razor page - exception.

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

My work 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), response will broke


Solution

  • First To send a POST request to the same URL (pathToPage) that you are attempting to fetch, utilize the get function posting to the same page that you are attempting to get is not common. Generally an API endpoint would get a POST request.

    and second reusing and redeclaring the Variable a con be confusing and prone to errors.

    you can try this:

    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);
      });
    }