Skip to content

Instantly share code, notes, and snippets.

@xyzdata

xyzdata/test.js

Forked from anonymous/test.js
Created Aug 22, 2017
Embed
What would you like to do?
Fetch API Post example
const promise = new Promise(
(resolve, reject) => {
// do a thing, possibly async, then…
if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
}
);
@xyzdata

This comment has been minimized.

Copy link
Owner Author

@xyzdata xyzdata commented Feb 24, 2018

Fetch & POST & CORS

xgqfrms/RAIO#45

@xyzdata

This comment has been minimized.

@xyzdata

This comment has been minimized.

Copy link
Owner Author

@xyzdata xyzdata commented Mar 19, 2018

curl

https://graphql.org/graphql-js/graphql-clients/

curl -X POST \
-H "Content-Type: application/json" \
-d '{"query": "{ hello }"}' \
http://localhost:4000/graphql

# curl -X POST -H "Content-Type: application/json" -d '{"query": "{ hello }"}' http://localhost:4000/graphql

XHR

var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open("POST", " http://localhost:8888/graphql");
// xhr.open("POST", "/graphql");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
// callback function
xhr.onload = function () {
    console.log('data returned:', xhr.response);
}
xhr.send(JSON.stringify({query: "{xyz{name}}"}));

fetch

// get
const url = `http://localhost:8888/graphql?query=query{xyz{name}}`;

fetch(url)
.then(res => res.json())
.then(json => {
    if(`data` in json){
        console.log(`json =\n`, JSON.stringify(json, null, 4));
    }else{
        // no data
        console.log(`json errors=\n`, JSON.stringify(json, null, 4));
    }
    
})
.catch(err => console.log(`error =`, err));


// post
// const url = `http://localhost:8888/graphql?query=query{xyz{name}}`;

fetch(url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        query: "{xyz{name}}"
    })
})
.then(res => res.json())
.then(json => {
    console.log(`json =\n`, JSON.stringify(json, null, 4));
})
.catch(err => console.log(`fetch post data error =`, err));
// console.log(`%c fetch post data!`, color);
@xyzdata

This comment has been minimized.

Copy link
Owner Author

@xyzdata xyzdata commented Mar 19, 2018

@xyzdata

This comment has been minimized.

Copy link
Owner Author

@xyzdata xyzdata commented Mar 30, 2018

POST bug

image

image

@xyzdata

This comment has been minimized.

Copy link
Owner Author

@xyzdata xyzdata commented Mar 30, 2018

body & string

image

string body & fetch post

image

https://davidwalsh.name/fetch

post & string body!

@xyzdata

This comment has been minimized.

Copy link
Owner Author

@xyzdata xyzdata commented Mar 30, 2018

POST & string body

OK

fetch(`http://123.456.146.144/user/manager`, {
    method: 'POST',
    mode: 'cors',
    headers: {
        'Content-Type': 'application/json',
    },
    body: `type=3&pid=10005&ucode=44003&id=18405&
    name=默认name&value=${json.items[0].value}`
})
.then(res => res.json())
.then(json => {
    console.log(`post return json =`, json);
})
.catch(error => console.error('POST Error:', error));;
@xyzdata

This comment has been minimized.

Copy link
Owner Author

@xyzdata xyzdata commented Mar 30, 2018

Fetch POST & String Body

no JSON.stringify()

fetch(`http://10.1.5.202//user/manager`, {
    method: 'POST',
    mode: 'cors',
    headers: {
        'Content-Type': 'application/json',
    },
    body: `type=3&pid=10005&ucode=44003&id=18405&name=默认name&value=${json.items[0].value}`,
    //  fetch post & string body
})
.then(res => res.json())
.then(json => {
    console.log(`post return json =`, json);
})
.catch(error => console.error('POST Error:', error));;




fetch(`http://10.1.5.202//user/manager`, {
    method: 'POST',
    mode: 'cors',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(`type=3&pid=10005&ucode=44003&id=18405&name=默认name&value=${json.items[0].value}`),
    //  fetch post & string body
    // JSON.stringify() & bug
})
.then(res => res.json())
.then(json => {
    console.log(`post return json =`, json);
})
.catch(error => console.error('POST Error:', error));;










fetch(`http://10.1.5.202//user/manager`, {
    method: 'POST',
    headers: {
        'Content-Type': 'multipart/form-data',
        // 'Content-Type': 'application/x-www-form-urlencoded',
        // 'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        type: 3,
        pid: 10005,
        ucode: 44003,
        id: 18405,
        name: `默认配置name`,
        value: json.items[0].value
    })
})
.then(res => res.json())
.then(json => {
    console.log(`fetch json =`, json);
});



var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open("POST", `http://10.1.5.202//user/manager`);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
// callback function
xhr.onload = function () {
    console.log('data returned:', xhr.response);
}
xhr.send(JSON.stringify({
    type: 3,
    pid: 10005,
    ucode: 44003,
    id: 18405,
    name: `默认配置name`,
    value: json.items[0].value
}));



fetch(`http://10.1.5.202//user/manager?type=3&pid=10005&ucode=44003&id=18405&name=默认name&value=${json.items[0].value}`, {
    method: 'POST',
    mode: 'cors',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        // 'Content-Type': 'application/json',
    },
})
.then(res => res.json())
.then(json => {
    console.log(`fetch json =`, json);
});



fetch(`http://10.1.5.202//user/manager?type=1&pid=10005&ucode=44003`)
.then(res => res.json())
.then(json => {
    console.log(`fetch json =`, json);
});



fetch(`http://10.1.5.202//user/manager?type=1&pid=10005&ucode=44003`, {
    method: 'GET',
    mode: 'cors',
    headers: {
        'Content-Type': 'application/json'
    },
})
.then(res => res.json())
.then(json => {
    console.log(`fetch json =`, json);
});



// fetch & POST
const postdata = () => {
    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            name: "new-name",
            password: "xyz&123"
        })
    });
};


// post
// const url = `http://localhost:8888/graphql?query=query{xyz{name}}`;

fetch(url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        query: "{xyz{name}}"
    })
})
.then(res => res.json())
.then(json => {
    console.log(`json =\n`, JSON.stringify(json, null, 4));
})
.catch(err => console.log(`fetch post data error =`, err));
// console.log(`%c fetch post data!`, color);





var url = 'https://example.com/profile';
var data = `username=example`;
// var data = {username: 'example'};

fetch(url, {
    method: 'POST', // or 'PUT'
    body: JSON.stringify(data), // data can be `string` or {object}!
    headers: new Headers({
        'Content-Type': 'application/json'
    })
})
.then(res => res.json())
.then(response => console.log('Success:', response))
.catch(error => console.error('Error:', error));
@xyzdata

This comment has been minimized.

Copy link
Owner Author

@xyzdata xyzdata commented May 8, 2018

fetch & POST

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Content-Type

image
image

let arr = ["org.gil.sydb.server.report.hkstock.topic.company_finance.report.PerformanceForecastReport"],
    query = `pro_name=org.gil.sydb.server.report&class_names=${JSON.stringify(arr)}`,
    url = `http://10.1.64.116:8080/http/send/svnlog`;
fetch(
    url,
    {
        method: "POST",
        mode: "cors",
        headers: {
            "Content-Type": "application/json",
        },
        body: query,
    }
)
.then(res => res.json())
.then(
    (json) => {
        return json;
    }
).catch(err => console.log(`fetch error`, err));

let arr = ["org.gil.sydb.server.report.hkstock.topic.company_finance.report.PerformanceForecastReport"],
    query = `pro_name=org.gil.sydb.server.report&class_names=${JSON.stringify(arr)}`,
    url = `http://10.1.64.116:8080/http/send/svnlog`;
fetch(
    url,
    {
        method: "POST",
        mode: "cors",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",// form default
        },
        body: query,
    }
)
.then(res => res.json())
.then(
    (json) => {
        return json;
    }
).catch(err => console.log(`fetch error`, err));
@xyzdata

This comment has been minimized.

Copy link
Owner Author

@xyzdata xyzdata commented May 8, 2018

Fetch POST & String Object & Form String

  1. Fetch POST & String Object

https://googlechrome.github.io/samples/fetch-api/fetch-post.html

// Content-Type: text/plain;charset=UTF-8
{
    method: 'post',
    body: JSON.stringify(opts)
}

image

String Object

image

Fetch POST JSON

image


  1. Fetch POST & Form String
// "Content-Type": "text/plain",// text
let query = `firstname=Mickey&lastname=Mouse `;
{
    method: 'post',
    body: JSON.stringify(query)
}
// "Content-Type": "application/x-www-form-urlencoded",// form default
{
    method: 'post',
    body:  `firstname=Mickey&lastname=Mouse`
}

https://www.w3schools.com/html/html_forms.asp
https://www.w3schools.com/html/tryit.asp?filename=tryhtml_form_submit

@xyzdata

This comment has been minimized.

Copy link
Owner Author

@xyzdata xyzdata commented May 8, 2018

Fetch POST All in One

FPAIO

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms 2016-present
 * @description Example POST method implementation:
 * @augments
 * @example
 * @reference_link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
 * @reference_link https://davidwalsh.name/fetch
 * @reference_link https://www.w3schools.com/html/html_forms.asp
 */

const postData = (url = ``, data = {}) => {
    // Default options are marked with *
    return fetch(url, {
        body: JSON.stringify(data), // must match "Content-Type" header
        cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
        credentials: "same-origin", // include, same-origin, *omit
        headers: {
            // "user-agent": "Mozilla/4.0 MDN Example",
            "Content-Type": "application/json",
            // "Content-Type": "text/plain",
            // "Content-Type": "text/plain",
        },
        method: "POST", // *GET, POST, PUT, DELETE, etc.
        mode: "cors", // no-cors, cors, *same-origin
        redirect: "follow", // manual, *follow, error
        referrer: "no-referrer", // *client, no-referrer
    })
    .then(response => response.json()) // parses response to JSON
    .then(json => {
        // json
        console.log(`json =`, JSON.stringify(json, null, 4));
        return json;
    })
    .catch(err => console.error(`error =`, err));
};




postData(
    "http://example.com/answer",
    {
        answer: 37
    }
).then(data => console.log(data)) // JSON from `response.json()` call
.catch(error => console.error(error));




// Promise &  Fetch POST
const fetchPOST = (url = `http://10.1.64.116:8080/http/send/svnlog`) => {
    let obj = {
            "pro_name":"org.gil.sydb.server.report",
            "class_names":["org.gil.sydb.server.report.hkstock.topic.company_finance.report.PerformanceForecastReport"]
        },
        query = `data=${JSON.stringify(obj)}`;
    return fetch(
        url,
        {
            method: "POST",
            mode: "cors",
            headers: {
                "Content-Type": "application/json",
            },
            // body: `type=3&pid=10005&ucode=44003&id=18405&name=默认name&value=${json.items[0].value}`
            body: JSON.stringify(query),
        }
    )
    .then(res => res.json())
    .then(
        (json) => {
            return json;
        }
    ).catch(err => console.log(`fetch error`, err));
};

// JSON Object String
const FetchPOSTJSONObjectString = () => {
    let arr = ["org.gil.sydb.server.report.hkstock.topic.company_finance.report.PerformanceForecastReport"],
        query = `pro_name=org.gil.sydb.server.report&class_names=${JSON.stringify(arr)}`,
        url = `http://10.1.64.116:8080/http/send/svnlog`;
    return fetch(
        url,
        {
            method: "POST",
            mode: "cors",
            headers: {
                "Content-Type": "application/json",
            },
            body: query,
        }
    )
    .then(res => res.json())
    .then(
        (json) => {
            return json;
        }
    ).catch(err => console.log(`fetch error`, err));
};


// Text String
const FetchPOSTText = () => {
    let arr = ["org.gil.sydb.server.report.hkstock.topic.company_finance.report.PerformanceForecastReport"],
        query = `pro_name=org.gil.sydb.server.report&class_names=${JSON.stringify(arr)}`,
        url = `http://10.1.64.116:8080/http/send/svnlog`;
    return fetch(
        url,
        {
            method: "POST",
            mode: "cors",
            headers: {
                "Content-Type": "text/plain",// text
            },
            body: query,
        }
    )
    .then(res => res.json())
    .then(
        (json) => {
            return json;
        }
    ).catch(err => console.log(`fetch error`, err));
};


// Form String
const FetchPOSTFormString = () => {
    let arr = ["org.gil.sydb.server.report.hkstock.topic.company_finance.report.PerformanceForecastReport"],
        query = `pro_name=org.gil.sydb.server.report&class_names=${JSON.stringify(arr)}`,
        url = `http://10.1.64.116:8080/http/send/svnlog`;
    return fetch(
        url,
        {
            method: "POST",
            mode: "cors",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",// form default
            },
            body: query,
        }
    )
    .then(res => res.json())
    .then(
        (json) => {
            return json;
        }
    ).catch(err => console.log(`fetch error`, err));
};

@xyzdata

This comment has been minimized.

Copy link
Owner Author

@xyzdata xyzdata commented May 8, 2018

@xgqfrms

This comment has been minimized.

Copy link

@xgqfrms xgqfrms commented May 9, 2020

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-05-09
 * @modified
 *
 * @description fetch-restful-all-in-one.js
 * @augments
 * @example
 * @link https://www.cnblogs.com/xgqfrms/p/9006886.html
 *
 */

const log = console.log;

const json = { id: '123', name: 'admin' };
const csrftoken = document.cookie.split(';').map(item => item.trim()).map(item => ({[item.split(`=`)[0]]: item.split(`=`)[1]})).filter(obj => obj.csrfToken)[0].csrfToken;;

const url = `http://localhost:7001/product/create`;

fetch(url, {
  headers: {
    "Content-Type": "application/json",
    "x-csrf-token": csrftoken,
  },
  credentials: "include",// cookie
  // credentials: "same-origin",
  method: "POST",
  mode: "cors",
  body: JSON.stringify(json),
})
// .then(res => res.text())
.then(res => res.json())
.then(json => {
  // log(`text =`, json);
  log(`json =`, JSON.stringify(json, null, 4));
  return json;
})
.catch(err => console.error(`error =`, err));


const update_url = `http://localhost:7001/product/update/123`;
fetch(update_url, {
  headers: {
    "Content-Type": "application/json",
    "x-csrf-token": csrftoken,
  },
  credentials: "include",
  method: "PUT",
  mode: "cors",
  body: JSON.stringify(json),
})
.then(res => res.json())
.then(json => {
  log(`json =`, JSON.stringify(json, null, 4));
  return json;
})
.catch(err => console.error(`error =`, err));


const delete_url = `http://localhost:7001/product/delete/123`;
fetch(delete_url, {
  headers: {
    "Content-Type": "application/json",
    "x-csrf-token": csrftoken,
  },
  credentials: "include",
  method: "DELETE",
  mode: "cors",
  body: JSON.stringify(json),
})
.then(res => res.json())
.then(json => {
  log(`json =`, JSON.stringify(json, null, 4));
  return json;
})
.catch(err => console.error(`error =`, err));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment