Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a server detect a request made with the fetch API?

I have an ASP.NET MVC 5 Application, which handles requests from my web site made with the fetch API. When an exception occurred in my controller, I use my custom "OnException" method, overriden from System.Web.Mvc.Controller, to send a result in JSON, containing data about the error. I do this because I don't want to send the default HTML error page. In this method, which is global for all controllers, I need to check if the request has been performed with the fetch API (if not, I don't do anything).

How can I do this ?

  • Should I add a custom http header to my requests ?
  • Should I add a specific parameter in all my requests ?
  • Do I have a totally wrong approach ?
like image 534
Climooo Avatar asked Aug 17 '16 12:08

Climooo


People also ask

How does the fetch API work?

The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.

How do you get data from an API using Fetch?

Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.

How do I read fetch API response?

To fetch a user we need: fetch('https://api.github.com/users/USERNAME') . If the response has status 200 , call . json() to read the JS object. Otherwise, if a fetch fails, or the response has non-200 status, we just return null in the resulting array.


2 Answers

Either of a specific header or a specific parameter would work; the "clean" approach would probably be to set the "Accept:" header in the fetch-sent request to "application/json", signalling that the said request is looking for a JSON response, and use that on the server-side to determine whether to send JSON or HTML.

like image 181
dontcallmedom Avatar answered Dec 10 '22 22:12

dontcallmedom


I think Accept Header does not help for the all scenarios. If you request HTML and you have a layout system and want to disable it for async request you will need a different approach.

Using a custom flag header is a more guarantied approach I think.

like image 38
Zortext Avatar answered Dec 10 '22 21:12

Zortext