Fetch POST All in One
https://www.cnblogs.com/xgqfrms/p/9006886.html
"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));
fetch api