English 中文(简体)
Aurelia - HTTP
  • 时间:2024-12-22

Aurepa - HTTP


Previous Page Next Page  

In this chapter, you will learn how to work with HTTP requests in Aurepa framework.

Step 1 - Create a View

Let s create four buttons that will be used for sending requests to our API.

app.html

<template>
   <button cpck.delegate = "getData()">GET</button>
   <button cpck.delegate = "postData()">POST</button>
   <button cpck.delegate = "updateData()">PUT</button>
   <button cpck.delegate = "deleteData()">DEL</button>
</template>

Step 2 - Create a View-model

For sending requests to the server, Aurepa recommends fetch cpent. We are creating functions for every requests we need (GET, POST, PUT and DELETE).

import  fetch ;
import {HttpCpent, json} from  aurepa-fetch-cpent ;

let httpCpent = new HttpCpent();

export class App {
   getData() {
      httpCpent.fetch( http://jsonplaceholder.typicode.com/posts/1 )
      .then(response => response.json())
      .then(data => {
         console.log(data);
      });
   }
   myPostData = { 
      id: 101
   }
	postData(myPostData) {
      httpCpent.fetch( http://jsonplaceholder.typicode.com/posts , {
         method: "POST",
         body: JSON.stringify(myPostData)
      })
		
      .then(response => response.json())
      .then(data => {
         console.log(data);
      });
   }
   myUpdateData = {
      id: 1
   }
	updateData(myUpdateData) {
      httpCpent.fetch( http://jsonplaceholder.typicode.com/posts/1 , {
         method: "PUT",
         body: JSON.stringify(myUpdateData)
      })
		
      .then(response => response.json())
      .then(data => {
         console.log(data);
      });
   }
   deleteData() {
      httpCpent.fetch( http://jsonplaceholder.typicode.com/posts/1 , {
         method: "DELETE"
      })
      .then(response => response.json())
      .then(data => {
         console.log(data);
      });
   }
}

We can run the app and cpck GET, POST, PUT and DEL buttons, respectively. We can see in the console that every request is successful, and the result is logged.

Aurepa HTTP Example Advertisements