.. include:: ../Includes.txt .. _examples_plain: ============ Basic requests ============ How to make a request with pure JavaScript ------------ .. tip:: | **Want to play, not read?** | Here is a ready-to-go codepen that demonstrates how to use VanillaJS for requests. Run and have fun! | `nnrestapi vanillajs demo `__ Sending a simple request (for modern browsers) ~~~~~~~~~~~~ If you can drop support for IE11 and below, the easiest way to send a request is using the promise-based ``fetch()`` command that comes with ES6+. Let's create a ``GET`` request to the nnrestapi backend: .. code-block:: javascript // By default this will be routed to Index->getIndexAction() const url = 'https://www.mywebsite.com/api/index'; fetch( url ) .then( async response => { // convert the result to a JavaScript-object let data = await response.json() if ( !response.ok ) { // reponse was not 200 alert( `Error ${response.status}: ${data.error}` ); } else { // everything ok! console.log( data ); } }); Without further configuration, ``fetch()`` will send a ``GET``-request. Of course you can also send a payload / JSON data to the backend using a ``POST``, ``PUT`` or ``PATCH`` request: .. code-block:: javascript // By default this will be routed to Index->postIndexAction() const url = 'https://www.mywebsite.com/api/index'; const json = { title: 'Title', text: 'Text to send', }; const xhrConfig = { method: 'POST', // or: 'PUT', 'PATCH', 'DELETE' ... headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(json) }; fetch( url, xhrConfig ) .then( async response => { let data = await response.json() if ( !response.ok ) { alert( `Error ${response.status}: ${data.error}` ); } else { console.log( data ); } }); VanillaJS Starter Template ~~~~~~~~~~~~ Here is a full example you can copy and paste to get you started. You can also test and play with it on `this codepen `__ .. code-block:: html nnrestapi VanillaJS Demo
Result