Wednesday, May 6, 2020

basic GET and POST with fetch

If you don't need IE support, "fetch" is a fine, library free option for doing GETs and POSTs and the like from the browser.

There's a little bit of ceremony that goes with them. Fetch returns a promise, and then many of the parsers (e.g. ".json()" and the other Body methods) also return a promise. Here's an example wrapper for function for GET:

function doJsonGet(url, fn, err) {
    fetch(url)
        .then((data) => {
            if (!data.ok) {
                throw Error(data.status);
            }
            return data.json();
        })
        .then((json) => {
            fn(json);
        })
        .catch((e) => {
            err(e);
        });
}

Here is the version for POST, which takes a bit more ceremony to set the Content-type and packup the payload...

function doJsonPost(url, content, fn, err) {
    const options = {
        method: 'POST',
        headers: {
            'Content-type': 'application/json',
        },
        body: JSON.stringify(content),
    };
    fetch(url, options)
        .then((data) => {
            if (!data.ok) {
                throw Error(data.status);
            }
            return data.json();
        })
        .then((json) => fn(json))
        .catch((e) => {
            err(e);
        });
}
I made up a cleaner and battle tested version here for GET, POST, PUT and DELETE

SEPTEMBER UPDATE:
I'm not sure why I get caught up in this code so often - subtle errors caused me to bork one take home job interview, and just now when I tried to copy and paste some other old code related to this, I had some weird problems, like sometimes what the code seemed to assume was a JSON encoded string was already an object, or a promise wasn't resolving quite right, etc.

ANYWAY. When making a JSON endpoint for an API in PHP, code like this seems to read in the POST data well:
function getJsonPOST() {
    return json_decode(file_get_contents('php://input'),true);
}

So my PHP test for POST was 
<? 
    $vals = getJsonPOST();  
    $res = array();
    $res['bar']=$vals['foo'] + 123;
    echo json_encode($res); 
   
function getJsonPOST() {
    return json_decode(file_get_contents('php://input'),true);
}
?>
and of course GET was just 
<?
    $val = $_GET['foo'];    
    $res['bar']=$val + 123;
    echo json_encode($res); 
?>
    
And I fired those off with this js:

    doJsonPost('server/test.php',{'foo':321},(res)=>{console.log(res);}, (res)=>{console.log('ERROR',res);});
    doJsonGet('server/testget.php?foo=432',(res)=>{console.log(res);}, (res)=>{console.log('ERROR',res);});
    

No comments:

Post a Comment