puter.net.fetch()


The puter fetch API lets you securely fetch a http/https resource without being bound by CORS restrictions.

Syntax

puter.net.fetch(url)
puter.net.fetch(url, options)

Parameters

url (String) (Required)

The url of the resource to access. The URL can be either http or https.

options (Object) (optional)

A standard RequestInit object

Return value

A Promise to a Response object.

Examples

<html>
<body>
    <script src="https://js.puter.com/v2/"></script>
    <script>
    (async () => { // run in async context so we can use await
        const request = await puter.net.fetch("https://example.com");
        puter.print(`Server sent status ${request.status} with message ${request.statusText} <br />`);
        for ([key, value] of request.headers.entries()) {
            puter.print(`Sent header ${key} with value ${value} <br />`);
        }
        
        const body = await request.text();
        puter.print("<code>Got body text<br />" + escapeHtml(body) + "</code>"); // escape body 
    })()

    // escape html characters
    function escapeHtml(unsafe) {
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
    }
    </script>
</body>
</html>