zoukankan      html  css  js  c++  java
  • xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

    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
            // cookies
            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));
    };
    
    





    
    "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));
    
    
    
    

    Flag Counter

    ©xgqfrms 2012-2020

    www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


  • 相关阅读:
    C# 基础知识系列- 11 委托和事件
    C# 基础知识系列- 10 反射和泛型(二)
    C# 基础知识系列- 9 字符串的更多用法(二)
    C# 基础知识系列- 9 字符串的更多用法(一)
    C# 基础知识系列- 8 Linq最后一部分查询表达式语法实践
    C# 基础知识系列- 6 Lambda表达式和Linq简单介绍
    C# 基础知识系列- 5 反射和泛型
    C# 基础知识系列- 4 面向对象
    TLS加密远程连接Docker
    树莓派4B安装64位Linux(不用显示器键盘鼠标)
  • 原文地址:https://www.cnblogs.com/xgqfrms/p/9006886.html
Copyright © 2011-2022 走看看