fetch 代替 XMLHttpRequest (json-server 模拟后台接口)

一、fetch 是 XMLHttpRequest 的替代方案。说白了就是除了 ajax 获取后台数据之外也可以用fetch 来获取。

二、fetch 的支持性还不是很好。挂载于BOM中可以通过浏览器直接访问。

  1.支持情况

  

  当然,如果不支持fetch也没有问题,可以使用第三方的ployfill来实现只会fetch:whatwg-fetch

三、JSON-SERVER模拟后台接口

  1.初始化项目 npm init

  2.安装JSON-SERVER:  npm install --save-dev json-server

  3.在跟目录下面创建一个db.json 写入

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}

  4.在package.json 中添加一段代码

"scripts": {
  "server": "json-server db.json", // 新加行
  "test": "..."
}

  5.npm run server

  

三个接口已经生成,支持post(新增) delete(删除) put(修改) get(查询);

关于JSON-SERVER 其他的配置我就不说了。有兴趣的自己去官网查看下。目前只是模拟一个后台接口。

四、GET请求。

1.

fetch(‘http://10.63.68.93:3000/profile‘, {
        method: ‘GET‘
    }).then((res)=>{
          return res.json()
    }).then(res => {
        console.log(res) //Object {name: "typicode"}
    })

2.get 请求参数的传递

把参数带在URL上面

 fetch(‘http://10.63.68.93:3000/profile?a=2&b=1‘, {
        method: ‘GET‘
    }).then((res)=>{
          return res.json()
    }).then(res => {
        console.log(res) //Object {name: "typicode"}
    })

五、POST请求

  1.与GET请求类似,POST请求的指定也是在fetch的第二个参数中:

fetch(‘http://10.63.68.93:3000/comments‘, {
        method: ‘POST‘
    }).then((res)=>{
        return res.json()
    }).then(res => {
        console.log(res) //Object {name: "typicode"}
    })

  2.POST请求的参数传递

var paramsString = "q=URLUtils.searchParams&topic=api"
    var searchParams = new URLSearchParams(paramsString);
    fetch(‘http://10.63.68.93:3000/posts‘, {
        method: ‘POST‘,
        body: searchParams // 这里是请求对象   具体api 去看fetch 官网的 URLSearchParams
    }).then((res)=>{
        return res.json()
    }).then(res => {
        console.log(res)
    })

六、设置请求头

let myHeaders = new Headers();

myHeaders.append(‘Content-Type‘, ‘text/xml‘);

myHeaders.get(‘Content-Type‘);
// should return ‘text/xml‘

  

var paramsString = "q=URLUtils.searchParams&topic=api"
    var searchParams = new URLSearchParams(paramsString);
    let myHeaders = new Headers();

    myHeaders.append(‘Content-Type‘, ‘text/xml‘);

    myHeaders.get(‘Content-Type‘);
    /*
    myHeaders = new Headers({
  "Content-Type": "text/plain",
  "Content-Length": content.length.toString(),
  "X-Custom-Header": "ProcessThisImmediately",
});

     */
    // should return ‘text/xml‘
    fetch(‘http://10.63.68.93:3000/posts‘, {
        method: ‘POST‘,
        headers:myHeaders,
        body: searchParams // 这里是请求对象   具体api 去看fetch 官网的 URLSearchParams
    }).then((res)=>{
        return res.json()
    }).then(res => {
        console.log(res)
    })

七、强制带cookie

  默认情况下, fetch 不会从服务端发送或接收任何 cookies, 如果站点依赖于维护一个用户会话,则导致未经认证的请求(要发送 cookies,必须发送凭据头).

八、fetch 封装ajax请求

/**
 * 将对象转成 a=1&b=2的形式
 * @param obj 对象
 */
function obj2String(obj, arr = [], idx = 0) {
  for (let item in obj) {
    arr[idx++] = [item, obj[item]]
  }
  return new URLSearchParams(arr).toString()
}

/**
 * 真正的请求
 * @param url 请求地址
 * @param options 请求参数
 * @param method 请求方式
 */
function commonFetcdh(url, options, method = ‘GET‘) {
  const searchStr = obj2String(options)
  let initObj = {}
  if (method === ‘GET‘) { // 如果是GET请求,拼接url
    url += ‘?‘ + searchStr
    initObj = {
      method: method,
      credentials: ‘include‘
    }
  } else {
    initObj = {
      method: method,
      credentials: ‘include‘,
      headers: new Headers({
        ‘Accept‘: ‘application/json‘,
        ‘Content-Type‘: ‘application/x-www-form-urlencoded‘
      }),
      body: searchStr
    }
  }
  fetch(url, initObj).then((res) => {
    return res.json()
  }).then((res) => {
    return res
  })
}

/**
 * GET请求
 * @param url 请求地址
 * @param options 请求参数
 */
function GET(url, options) {
  return commonFetcdh(url, options, ‘GET‘)
}

/**
 * POST请求
 * @param url 请求地址
 * @param options 请求参数
 */
function POST(url, options) {
  return commonFetcdh(url, options, ‘POST‘)
}

原文地址:https://www.cnblogs.com/createGod/p/8472811.html

时间: 2024-08-17 11:54:27

fetch 代替 XMLHttpRequest (json-server 模拟后台接口)的相关文章

使用electron开发一个h5的客户端应用创建http服务模拟后台接口mock

使用electron开发一个h5的客户端应用创建http服务模拟后端接口mock 在上一篇<electron快速开始>里讲述了如何快速的开始一个electron的应用程序,既然electron是可以直接使用node环境编写程序的,那么我们就可以有很多可以处理的事,比如我们可以做个可视化的前端构建工具,或者我们可以建一个后台的管理系统.基于这两天,我简单的做了一个模拟后端接口的http服务. 它可以完成如下功能: 它可以创建http本地服务 它可以模拟后端的多种请求方式,如get.post.pu

vue-cli搭建项目模拟后台接口数据,webpack-dev-conf.js文件配置

首先第一步 const express = require('express') const app = express() var appData = require('../data.json') var seller = appData.seller var goods = appData.goods var ratings =appData.ratings var apiRoutes = express.Router() app.use('/api',apiRoutes) 第二步找到de

通过 Ajax 调取后台接口将返回的 json 数据绑定在页面上

第一步: 编写基础的 html 框架内容,并引入 jquery: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>测试Ajax</title> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"><

fetch和XMLHttpRequest讲解

写在前面 fetch 同 XMLHttpRequest 非常类似,都是用来做网络请求.但是同复杂的XMLHttpRequest的API相比,fetch使用了Promise,这让它使用起来更加简洁,从而避免陷入"回调地狱". 两者比较 比如,如果我们想要实现这样一个需求:请求一个URL地址,获取响应数据并将数据转换成JSON格式.使用fetch和XMLHttpRequest实现的方式是不同的. 使用XMLHttpRequest实现 使用XMLHttpRequest来实现改功能需要设置两个

干货运用resteasy整合web框架,同时将后台接口以js形式导出到前台

不多说先上 web.xml配置 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/jav

json server的简单使用(附:使用nodejs快速搭建本地服务器)

作为前端开发人员,经常需要模拟后台数据,我们称之为mock.通常的方式为自己搭建一个服务器,返回我们想要的数据.json server 作为工具,因为它足够简单,写少量数据,即可使用. 安装 首先需要安装nodejs,建议使用最新版本.然后全局安装json server. npm install json-server -g 安装完成后可以用 json-server -h 命令检查是否安装成功,成功后会出现json-server相关的参数选项. 运行 安装完成后,可以在任一目录下建立一个 xxx

使用Ajax与后台接口Api交互(以登陆功能为例)

首先,要做这个功能前,我们必须先查阅后台接口文档,了解使用登录接口时,需要提交哪些参数,并且接口使用返回的数据. 这里我使用了一个返回json格式数据的登录接口为例,讲解怎么使用Ajax与后台接口交互. 开发文档 由上图开发文档里,我们可以清楚的知道,要使用这个登录接口,我们只需要提交账号adminName和密码pwd两个参数. 二.编写javascript(Ajax)实现登录 var xmlhttp; if (window.XMLHttpRequest){//IE7+, Firefox, Ch

Swagger结合mustache模板生成后台接口代码、以及前后台建模代码

之前项目中使用的的thrift来建模,维护前后台模型以及rest接口,前台使用的是angular2: 但是使用thrift只能生成建模,后台的rest接口的Controller文件还是需要手动去写,一旦接口改动就会涉及到很多方面. 由此准备使用Swagger和mustache模板来做一个maven插件直接生成前台ts文件和后台java文件以及rest接口文件.只需要维护swagger的yaml文件. yaml文件: swagger: "2.0"info: description: &q

fetch和XMLHttpRequest

除了XMLHttpRequest对象来获取后台的数据之外,还可以使用一种更优的解决方案fetch. 到现在为止,fetch的支持性还不是很好,但是在谷歌浏览器中已经支持了fetch.fetch挂在在BOM中,可以直接在谷歌浏览器中使用. 查看fetch的支持情况:fetch的支持情况 当然,如果不支持fetch也没有问题,可以使用第三方的ployfill来实现只会fetch:whatwg-fetch 下面我们来写第一个fetch获取后端数据的例子: // 通过fetch获取百度的错误提示页面 f