အကြောင်းအရာသို့ ကရန်

Node.js ပေါင်းစပ်မှု

SMSBAT API ကို သင်၏ Node.js အပလီကေးရှင်းတွင် ပေါင်းစည်းခြင်းသည် မူရင်း fetch API (Node.js 18+) သို့မဟုတ် လူကြိုက်များသော axios စာကြည့်တိုက်ကို အသုံးပြု၍ လုပ်ဆောင်နိုင်သည်။

Axios ကိုအသုံးပြုခြင်း (အကြံပြုထားသည်)

ပထမဦးစွာ npm သို့မဟုတ် yarn မှတဆင့် Axios ကို ထည့်သွင်းပါ။

npm install axios
# or
yarn add axios

ထို့နောက် စာတိုပေးပို့ရန် အောက်ပါကုဒ်ကို အသုံးပြုပါ။

const axios = require('axios');

async function sendMessage() {
  const url = 'https://api.smsbat.com/bat/messagelist';
  const apiKey = 'YOUR_API_KEY_HERE';

  const payload = {
    messages: [
      {
        from: 'ALPHANAME',
        to: '380501234567',
        text: 'Hello from Node.js and Axios!',
        type: 'sms'
      }
    ]
  };

  try {
    const response = await axios.post(url, payload, {
      headers: {
        'Content-Type': 'application/json',
        'X-Authorization-Key': apiKey
      },
      timeout: 10000
    });

    console.log(`Status Code: ${response.status}`);
    console.log('Response:', response.data);
  } catch (error) {
    console.error('An error occurred:', error.message);
    if (error.response) {
      console.error('Error Details:', error.response.data);
    }
  }
}

sendMessage();

Native Fetch ကိုအသုံးပြုခြင်း (Node.js 18+)

အကယ်၍ သင်သည် Node.js 18 နှင့်အထက်ကို အသုံးပြုနေပါက၊ သင်သည် built-in global fetch API ကို အသုံးပြုနိုင်ပါသည်။

async function sendMessageWithFetch() {
  const url = 'https://api.smsbat.com/bat/messagelist';
  const apiKey = 'YOUR_API_KEY_HERE';

  const payload = {
    messages: [
      {
        from: 'ALPHANAME',
        to: '380501234567',
        text: 'Hello from Node.js Native Fetch!',
        type: 'sms'
      }
    ]
  };

  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Authorization-Key': apiKey
      },
      body: JSON.stringify(payload)
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}, details: ${JSON.stringify(data)}`);
    }

    console.log(`Status Code: ${response.status}`);
    console.log('Response:', data);
  } catch (error) {
    console.error('An error occurred:', error.message);
  }
}

sendMessageWithFetch();