Altbilgi içeriğine atla
NODE YARDıM

Node.js Fetch (Geliştiriciler İçin Nasıl Çalışır)

Node Fetch, Node.js ekosisteminde, HTTP isteklerini basit ve sezgisel hale getirmek için tasarlanmış popüler hafif bir modüldür. Tarayıcı ortamında bulunan Fetch API'sinden ilham alarak, web API'leriyle etkileşimi hafif ve tanıdık bir şekilde sağlar. Node-fetch, Node.js'de Fetch API desteği sunarak, servis çalışanlarının HTTP başlıklarını yönetmesine ve fetch HTTPS isteklerini verimli bir şekilde gerçekleştirmesine olanak tanır.

Bu makale, Node-fetch'in ana özelliklerini ve kullanımını keşfetmenize yardımcı olacak ve Node.js'de HTTP istek işleme süreçlerini basitleştirmek isteyen geliştiriciler için kapsamlı bir kılavuz sunacaktır. Ayrıca, programcıların PDF oluşturmasına ve düzenlemesine, HTML içeriğini PDF'ye dönüştürmesine ve daha fazlasına olanak tanıyan bir Node.js PDF kütüphanesi olan IronPDF'yi de kullanacağız.

Node.js fetch nedir?

Node fetch, Fetch API'yi Node.js'ye getiren bir modüldür. Fetch API, modern bir HTTP istek arayüzü olup genellikle web tarayıcılarında kullanılır. Node.js fetch, bu işlevselliği kopyalayarak, Node.js uygulamalarının HTTP isteklerini aynı kolaylık ve basitlikle gerçekleştirmesine olanak tanır. Bu, Fetch API'ye zaten aşina olan geliştiriciler veya Node.js uygulamalarında HTTP isteklerini yönetmek için basit bir yol arayanlar için harika bir seçenektir.

Node.js Fetch (Geliştiriciler için Nasıl Çalışır): Şekil 1 - Node.js Fetch

Node.js Fetch'in Ana Özellikleri

1. Basitlik ve Aşinalık

Node.js fetch, tarayıcılarda bulunan Fetch API'yi taklit ederek, geliştiriciler için basit ve tanıdık bir arayüz sağlar.

2. Promise Tabanlı

Fetch API gibi, Node.js fetch de promise tabanli calisir ve geliştiricilerin asenkron kod yazmasini daha okunabilir ve yonetilebilir bir sekilde saglar.

3. Hafif

Node.js fetch minimalistik bir kutuphanedir, bu da onu hizli ve verimli yapar. Daha buyuk HTTP kutuphanelerinin faydalariyla gelmez, uygulamanizi hafif tutar.

4. Uyumluluk

Node.js fetch, genis bir HTTP metodu, baslik ve yanit tipi yelpazesini destekler, bu da onu son derece çok yonlu yapar.

5. Yayın Akışı

Büyük yükleri verimli bir şekilde işlemek için yararlı olan yayın yapan yanıtları destekler.

Node.js Fetch'i Yükleme

Node-fetch ile başlamak icin, npm (Node Package Manager) uzerinden yuklemeniz gerekir. Proje dizininizde asagidaki komutu calistirin:

npm install node-fetch
npm install node-fetch
SHELL

Temel Kullanımı

Node.js fetch ile bir GET isteginin nasıl yapilacagina dair basit bir örnek sunulmustur:

import fetch from 'node-fetch';

const url = 'https://jsonplaceholder.typicode.com/posts';

// Make a GET request to fetch data
fetch(url)
    .then(response => {
        // Check if the response status is OK
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        // Parse the response as JSON
        return response.json();
    })
    .then(data => {
        // Process the JSON data
        console.log(data);
    })
    .catch(error => {
        // Handle any errors that occur during the fetch
        console.error('There has been a problem with your fetch operation:', error);
    });
import fetch from 'node-fetch';

const url = 'https://jsonplaceholder.typicode.com/posts';

// Make a GET request to fetch data
fetch(url)
    .then(response => {
        // Check if the response status is OK
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        // Parse the response as JSON
        return response.json();
    })
    .then(data => {
        // Process the JSON data
        console.log(data);
    })
    .catch(error => {
        // Handle any errors that occur during the fetch
        console.error('There has been a problem with your fetch operation:', error);
    });
JAVASCRIPT

Bu kod parcasi, bir API'den JSON verileri almak icin yapilan basit bir GET istegini göstermektedir. fetch fonksiyonu, yanit nesnesine cozumlenen bir promise dondurur. Daha sonra yanitlari donduren metodlari, yanit govdesini parcayarak okuyan json() gibi cagri yaparak kullanabilirsiniz.

Konsol Çıkışı

Node.js Fetch (Geliştiriciler Icin Nasıl Calisir): Sekil 2 - Node.js fetch kullanarak

Gelişmiş Kullanim

Node.js fetch, POST istekleri yapma, ozellestirilmis istek basliklari ayarlama ve farkli yanit turlerini işleme gibi daha gelişmiş özellikler de destekler.

Bir POST İsteği Yapma

import fetch from 'node-fetch';

const url = 'https://jsonplaceholder.typicode.com/posts';
const data = { key: 'value' };

// Make a POST request with JSON payload
fetch(url, {
    method: 'POST',
    headers: {
        // Specify content type as JSON
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
})
    .then(response => {
        // Check if the response status is OK
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        // Parse the response as JSON
        return response.json();
    })
    .then(data => {
        // Process the JSON data
        console.log(data);
    })
    .catch(error => {
        // Handle any errors that occur during the fetch
        console.error('There has been a problem with your fetch operation:', error);
    });
import fetch from 'node-fetch';

const url = 'https://jsonplaceholder.typicode.com/posts';
const data = { key: 'value' };

// Make a POST request with JSON payload
fetch(url, {
    method: 'POST',
    headers: {
        // Specify content type as JSON
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
})
    .then(response => {
        // Check if the response status is OK
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        // Parse the response as JSON
        return response.json();
    })
    .then(data => {
        // Process the JSON data
        console.log(data);
    })
    .catch(error => {
        // Handle any errors that occur during the fetch
        console.error('There has been a problem with your fetch operation:', error);
    });
JAVASCRIPT

Bu örnek, JSON yuklenmis bir POST isteginin nasıl gonderilecegini göstermektedir. headers secenegi, yanitin iceri tipini belirtmek icin kullanilir ve body secenegi serilestirilmis JSON verilerini icerir.

Konsol Çıkışı

Node.js Fetch (Geliştiriciler Icin Nasıl Calisir): Sekil 3 - Node.js fetch kullanarak

Yayın Yanıtlarını İşleme

import fetch from 'node-fetch';
import fs from 'fs';

const url = 'https://jsonplaceholder.typicode.com/posts';

// Make a GET request to fetch data and stream it to a file
fetch(url)
    .then(response => {
        // Check if the response status is OK
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        // Pipe the response body as a file stream to 'large-data.json'
        const dest = fs.createWriteStream('./large-data.json');
        response.body.pipe(dest);
    })
    .catch(error => {
        // Handle any errors that occur during the fetch
        console.error('There has been a problem with your fetch operation:', error);
    });
import fetch from 'node-fetch';
import fs from 'fs';

const url = 'https://jsonplaceholder.typicode.com/posts';

// Make a GET request to fetch data and stream it to a file
fetch(url)
    .then(response => {
        // Check if the response status is OK
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        // Pipe the response body as a file stream to 'large-data.json'
        const dest = fs.createWriteStream('./large-data.json');
        response.body.pipe(dest);
    })
    .catch(error => {
        // Handle any errors that occur during the fetch
        console.error('There has been a problem with your fetch operation:', error);
    });
JAVASCRIPT

Bu örnekte, yanit govdesi, buyuk yanitlarin verimli bir sekilde nasıl isleyecegini göstermek amaciyla bir dosya akis olarak sunucuya baglanir.

ÇIKTI

Node.js Fetch (Geliştiriciler Icin Nasıl Calisir): Sekil 4 - Çıktı dosyası: large-data.json

Hata Yönetimi

HTTP istekleriyle calisirken dogru hata yonetimi çok onemlidir. Node.js fetch, promise'leri kullanarak hatalari yakalamak ve işlemek icin acik bir yol saglar.

fetch(url)
    .then(response => {
        // Check if the response status is OK
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        // Parse the response as JSON
        return response.json();
    })
    .then(data => {
        // Process the JSON data
        console.log(data);
    })
    .catch(error => {
        // Handle any errors that occur during the fetch
        console.error('Fetch error:', error);
    });
fetch(url)
    .then(response => {
        // Check if the response status is OK
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        // Parse the response as JSON
        return response.json();
    })
    .then(data => {
        // Process the JSON data
        console.log(data);
    })
    .catch(error => {
        // Handle any errors that occur during the fetch
        console.error('Fetch error:', error);
    });
JAVASCRIPT

Burada, yanit durumu 200-299 araliginda degilse bir hata atilir ve catch bölümu istek sirasinda meydana gelen hatalari isler. Aksi takdirde, gecerli JSON yaniti dondurulur.

Node.js fetch ile IronPDF kullanarak Node.js'te PDF Oluşturmak

Node fetch, Node.js ekosisteminde HTTP fetch istekleri yapmak icin yaygin olarak kullanilan bir kutuphanedir. IronPDF ile birlestiginde, çeşitli web kaynaklarindan PDFler oluşturmak icin çok yonlu bir arac haline gelir.

IronPDF nedir?

IronPDF, geliştiricilerin PDF'ler oluşturmasina, duzenlemesine ve içerik cikarmasina guclu ve etkili bir sekilde izin veren saglam bir kutuphanedir. C#, Python, Java ve Node.js icin kullanilabilir olan IronPDF, kullaniciyla dost API'si ile PDF işleme isini basit hale getirir.

Node.js Fetch (Geliştiriciler Icin Nasıl Calisir): Sekil 5 - Node.js icin IronPDF: Node.js PDF Kutuphanesi

IronPDF Kitapligini Yükleme

Oncelikle, projenize IronPDF'i yüklemeniz gerekir. Kutuphaneyi yüklemek icin asagidaki npm komutunu kullanin:

 npm i @ironsoftware/ironpdf

Web içerik kaynaklarindan PDF oluşturmak icin Node.js fetch ile IronPDF kullanimini kesfedin.

Node.js fetch ve IronPDF'i Birleştirme

Web icerigi dinamik olarak almak ve PDFler oluşturmak icin Node.js fetch ve IronPDF'i birlestirebilirsiniz. Ornegin, bir API'nin son noktasindan veri almak, dinamik HTML oluşturmak ve onu PDF'e dönüştürmek isteyebilirsiniz. Asagidaki örnek, bu gorevin nasıl gerçekleştirilebilecegini göstermektedir:

import fetch from 'node-fetch';
import { PdfDocument } from '@ironsoftware/ironpdf';

(async () => {
    // Replace the apiUrl with the actual URL
    const apiUrl = "https://jsonplaceholder.typicode.com/posts";

    // Fetch data from API
    const response = await fetch(apiUrl);
    const data = await response.json();

    // Create dynamic HTML content with a table
    const htmlContent = `
        <!DOCTYPE html>
        <html>
        <head>
            <title>Data Report</title>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    margin: 40px;
                }
                table {
                    width: 100%;
                    border-collapse: collapse;
                }
                table, th, td {
                    border: 1px solid black;
                }
                th, td {
                    padding: 10px;
                    text-align: left;
                }
                th {
                    background-color: #f2f2f2;
                }
                h1 {
                    text-align: center;
                }
            </style>
        </head>
        <body>
            <h1>Data Report</h1>
            <table>
                <tr>
                    <th>User ID</th>
                    <th>ID</th>
                    <th>Title</th>
                    <th>Body</th>
                </tr>
                ${data.map(item => `
                    <tr>
                        <td>${item.userId}</td>
                        <td>${item.id}</td>
                        <td>${item.title}</td>
                        <td>${item.body}</td>
                    </tr>
                `).join('')}
            </table>
        </body>
        </html>
    `;

    // Generate PDF from the HTML string
    const pdfFromHtmlString = await PdfDocument.fromHtml(htmlContent);
    await pdfFromHtmlString.saveAs("dynamic_report.pdf");
    console.log("PDF generated from API data successfully!");
})();
import fetch from 'node-fetch';
import { PdfDocument } from '@ironsoftware/ironpdf';

(async () => {
    // Replace the apiUrl with the actual URL
    const apiUrl = "https://jsonplaceholder.typicode.com/posts";

    // Fetch data from API
    const response = await fetch(apiUrl);
    const data = await response.json();

    // Create dynamic HTML content with a table
    const htmlContent = `
        <!DOCTYPE html>
        <html>
        <head>
            <title>Data Report</title>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    margin: 40px;
                }
                table {
                    width: 100%;
                    border-collapse: collapse;
                }
                table, th, td {
                    border: 1px solid black;
                }
                th, td {
                    padding: 10px;
                    text-align: left;
                }
                th {
                    background-color: #f2f2f2;
                }
                h1 {
                    text-align: center;
                }
            </style>
        </head>
        <body>
            <h1>Data Report</h1>
            <table>
                <tr>
                    <th>User ID</th>
                    <th>ID</th>
                    <th>Title</th>
                    <th>Body</th>
                </tr>
                ${data.map(item => `
                    <tr>
                        <td>${item.userId}</td>
                        <td>${item.id}</td>
                        <td>${item.title}</td>
                        <td>${item.body}</td>
                    </tr>
                `).join('')}
            </table>
        </body>
        </html>
    `;

    // Generate PDF from the HTML string
    const pdfFromHtmlString = await PdfDocument.fromHtml(htmlContent);
    await pdfFromHtmlString.saveAs("dynamic_report.pdf");
    console.log("PDF generated from API data successfully!");
})();
JAVASCRIPT

Çıktı PDF

JSON yanit ciktisi zarif bir sekilde HTML tablosuna eslenir ve IronPDF tarziyla birlikte dogru bir sekilde dönüştürur.

Node.js Fetch (Geliştiriciler Icin Nasıl Calisir): Sekil 6 - HTML dizesi IronPDF kullanılarak doğru bir şekilde PDF'e dönüştürüldü.

IronPDF ve fonksiyonlari hakkinda daha fazla ayrinti icin, lutfen bu dokümantasyon sayfasina bakin.

Sonuç

Node fetch Node.js'de HTTP istekleri yapmak icin guclu ama basit bir aractir. Tanim getiren API'si, promise tabanlı yaklaşımi ve hafif yapisi sayesinde hem yeni başlayanlar hem de deneyimli geliştiriciler icin harika bir secimdir. Ister temel GET istekleri yapiyor olun, ister ozellestirilmis basliklara sahip karmasik POST istekleri ile ilgileniyor olun, Node fetch web API'leri ile etkili bir sekilde etkilesime gecmenin temiz bir yolunu sunar.

Node fetch ile IronPDF'i birlestirerek, Node.js'de çeşitli web içerik kaynaklarindan PDF'ler oluşturmak icin guclu ve esnek bir yol elde edebilirsiniz. Bu iki kutuphaneyi entegre ederek, web verilerinden faydalanan ve profesyonel PDF'ler oluşturan guclu uygulamalar geliştirebilirsiniz.

IronPDF $799 ile başlıyor. Guclu PDF oluşturma özelliklerini risksiz deneyimleyin. Bugun deneyin ve farki kendiniz gorun!

Darrius Serrant
Tam Yığın Yazılım Mühendisi (WebOps)

Darrius Serrant, Miami Üniversitesi'nden Bilgisayar Bilimleri lisans derecesine sahiptir ve Iron Software'de Tam Yığın WebOps Pazarlama Mühendisi olarak çalışmaktadır. Küçük yaşlardan itibaren kodlamaya ilgi duyan Darrius, bilişimi hem gizemli hem de erişilebilir buldu ve onu yaratıcılık ve problem çö...

Daha Fazlasını Oku

Iron Destek Ekibi

Haftanın 5 günü, 24 saat çevrimiçiyiz.
Sohbet
E-posta
Beni Ara