Aurelia - HTTP



在本章中,您將瞭解如何在 Aurelia 框架中使用 HTTP 請求。

第 1 步 - 建立檢視

讓我們建立四個按鈕,用於向我們的 API 傳送請求。

app.html

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

第 2 步 - 建立視模型

為了向伺服器傳送請求,Aurelia 推薦使用 **fetch** 客戶端。我們為需要的每個請求(GET、POST、PUT 和 DELETE)建立函式。

import 'fetch';
import {HttpClient, json} from 'aurelia-fetch-client';

let httpClient = new HttpClient();

export class App {
   getData() {
      httpClient.fetch('http://jsonplaceholder.typicode.com/posts/1')
      .then(response => response.json())
      .then(data => {
         console.log(data);
      });
   }
   myPostData = { 
      id: 101
   }
	postData(myPostData) {
      httpClient.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) {
      httpClient.fetch('http://jsonplaceholder.typicode.com/posts/1', {
         method: "PUT",
         body: JSON.stringify(myUpdateData)
      })
		
      .then(response => response.json())
      .then(data => {
         console.log(data);
      });
   }
   deleteData() {
      httpClient.fetch('http://jsonplaceholder.typicode.com/posts/1', {
         method: "DELETE"
      })
      .then(response => response.json())
      .then(data => {
         console.log(data);
      });
   }
}

我們可以執行該應用程式,分別單擊 **GET**、**POST**、**PUT** 和 **DEL** 按鈕。我們可以在控制檯中看到每個請求都已成功,並且結果已記錄。

Aurelia HTTP Example
廣告
© . All rights reserved.