Skip to content

Instantly share code, notes, and snippets.

@xyzdata
Forked from anonymous/test.js
Created August 22, 2017 06:07
Show Gist options
  • Save xyzdata/3b01b5d4e9e5698058f3def689126bc2 to your computer and use it in GitHub Desktop.
Save xyzdata/3b01b5d4e9e5698058f3def689126bc2 to your computer and use it in GitHub Desktop.
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"));
}
}
);
@xgqfrms
Copy link

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