-
-
Save xyzdata/3b01b5d4e9e5698058f3def689126bc2 to your computer and use it in GitHub Desktop.
Fetch API Post example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")); | |
} | |
} | |
); |
"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
http://www.cnblogs.com/xgqfrms/p/9006886.html