Monday 2 May 2022

Tutorial: Call an ASP.NET Core web API with JavaScript

https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-javascript?view=aspnetcore-6.0

Some quotes from the tutorial page

How to call an ASP.NET Core web API with JavaScript, using the Fetch API.

The fetch function returns a Promise object, which contains an HTTP response represented as a Response object. 

A common pattern is to extract the JSON response body by invoking the json function on the Response object.


Get a list

const uri = 'api/todoitems';

let todos = [];


function getItems() {

    fetch(uri)

        .then(response => response.json())

        .then(data => _displayItems(data))

        .catch(error => console.error('Unable to get items.', error));

}


By changing launchSettings.json >> launchUrl remove, the project chagnes from API project to js html project.

Before :



After:


Add an item

fetch(uri, {

    method: 'POST',


Update

fetch(`${uri}/${itemId}`, {

  method: 'PUT',

No comments:

Post a Comment