การใช้งาน API ด้วย JavaScript / TypeScript

ท่านสามารถใช้ API ได้ทั้งจาก Frontend หรือ Backend โดยแสดงตัวอย่างในภาษา JavaScript / TypeScript. นอกจากนี้ หากอยู่ใน Frontend mode ท่านสามารถเลือกได้ว่าจะใช้ Vanilla JS, React, Vue หรือ Angular.

Language:
Environment:
Framework (Frontend Only):

ขอรับ Token (refresh-token และ access-token)

เริ่มด้วยการขอรับ refresh-token และ access-token โดยใช้ username และ password ที่ลงทะเบียนแล้ว

frontend-vanilla.js (Frontend - Vanilla JS)

async function getTokens() {
    const response = await fetch('https://hcode.moph.go.th/api/token/', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({username: 'your_username', password: 'your_password'})
    });
    return response.json();
}

(async () => {
    const tokens = await getTokens();
    console.log(tokens);
})();
frontend-vanilla.ts (Frontend - Vanilla TS)

interface TokenResponse {
    refresh: string;
    access: string;
}

async function getTokens(): Promise {
    const response = await fetch('https://hcode.moph.go.th/api/token/', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({username: 'your_username', password: 'your_password'})
    });
    return response.json() as Promise;
}

(async () => {
    const tokens = await getTokens();
    console.log(tokens);
})();
frontend-react.js (Frontend - React JS)

import { useEffect } from 'react';

function App() {
  useEffect(() => {
    async function fetchTokens() {
      const response = await fetch('https://hcode.moph.go.th/api/token/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username: 'your_username', password: 'your_password' })
      });
      const tokens = await response.json();
      console.log(tokens);
    }
    fetchTokens();
  }, []);

  return 
Check console for tokens
; } export default App;
frontend-react.tsx (Frontend - React TS)

import React, { useEffect } from 'react';

interface TokenResponse {
    refresh: string;
    access: string;
}

const App: React.FC = () => {
  useEffect(() => {
    async function fetchTokens() {
      const response = await fetch('https://hcode.moph.go.th/api/token/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username: 'your_username', password: 'your_password' })
      });
      const tokens: TokenResponse = await response.json();
      console.log(tokens);
    }
    fetchTokens();
  }, []);

  return 
Check console for tokens
; }; export default App;
frontend-vue.js (Frontend - Vue JS)

export default {
  name: 'App',
  async mounted() {
    const response = await fetch('https://hcode.moph.go.th/api/token/', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username: 'your_username', password: 'your_password' })
    });
    const tokens = await response.json();
    console.log(tokens);
  },
  template: `
Check console for tokens
` }
frontend-vue.ts (Frontend - Vue TS)

import { defineComponent, onMounted } from 'vue';

interface TokenResponse {
    refresh: string;
    access: string;
}

export default defineComponent({
  name: 'App',
  setup() {
    onMounted(async () => {
      const response = await fetch('https://hcode.moph.go.th/api/token/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username: 'your_username', password: 'your_password' })
      });
      const tokens: TokenResponse = await response.json();
      console.log(tokens);
    });

    return {};
  },
  template: `
Check console for tokens
` });
frontend-angular.js (Frontend - Angular)

// Angular มีเฉพาะ TypeScript ไม่มี JavaScript
frontend-angular.ts (Frontend - Angular TS)

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

interface TokenResponse {
  refresh: string;
  access: string;
}

@Component({
  selector: 'app-root',
  template: `
Check console for tokens
` }) export class AppComponent implements OnInit { constructor(private http: HttpClient) {} ngOnInit() { this.http.post('https://hcode.moph.go.th/api/token/', { username: 'your_username', password: 'your_password' }).subscribe(tokens => { console.log(tokens); }); } }
server.js (Backend - JS)

const express = require('express');
const fetch = require('node-fetch');

const app = express();
app.use(express.json());

app.post('/login', async (req, res) => {
    const { username, password } = req.body;
    const response = await fetch('https://hcode.moph.go.th/api/token/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password })
    });
    const tokens = await response.json();
    res.json(tokens);
});

app.listen(3000, () => console.log('Backend running on http://localhost:3000'));
server.ts (Backend - TS)

import express from 'express';
import fetch from 'node-fetch';

const app = express();
app.use(express.json());

interface TokenResponse {
    refresh: string;
    access: string;
}

app.post('/login', async (req, res) => {
    const { username, password } = req.body;
    const response = await fetch('https://hcode.moph.go.th/api/token/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password })
    });
    const tokens: TokenResponse = await response.json();
    res.json(tokens);
});

app.listen(3000, () => console.log('Backend running on http://localhost:3000'));

สรุป