fetch基本使用

搭建简易的服务器:

  ①新建express文件夹

  ②终端中执行 express -e 和 npm i

  ③在express/routes/user.js中定义login请求路径

复制代码
    var express = require('express')
    var router = express.Router()

    router.get('/login', (req, res) => {
      let { username, password } = req.query
      console.log(username, password)
      if (username === 'admin' && password === 'admin') {
        res.json({
          code: 200,
          data: 'OK'
        })
      } else {
        res.json({
          code: 200,
          data: {
            info: '用户名或密码错误'
          }
        })
      }
    })

    router.post('/login', (req, res) => {
      let { username, password } = req.body
      console.log(username, password)
      if (username === 'admin' && password === 'admin') {
        res.json({
          code: 200,
          data: 'OK'
        })
      } else {
        res.json({
          code: 200,
          data: {
            info: '用户名或密码错误'
          }
        })
      }
    })

    module.exports = router
View Code
复制代码

  ④dev.config.js中配置跨域代理

  

  ⑤package.json中用supervisor替换原来的node,重启服务:npm start

    "scripts": {
      "start": "supervisor ./bin/www"
    },

 

react中使用fetch:

  ①下载插件:npm i whatwg-fetch

  ②组件中引入和使用

    import { fetch as fetchPolyfill } from 'whatwg-fetch' // 起一个别名,防止和原生的fetch冲突

    fetch的第一个then方法中返回结果集,需要在这里对数据进行处理,设置希望返回的数据类型

    

      componentDidMount() {
        fetchPolyfill('/users/login?username=admin&password=admin')
          .then((res) => res.json())
          .then((data) => {
            console.log(data) // 这儿的data就是 express 中 res.json() 中的对象
          })
      }

  post请求:需要下载qs依赖,post请求需要设置method和headers,body参数需要用qs模块转为查询字符串

复制代码
      fetchPolyfill('/users/login', {
        method: 'post',
        headers: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        body: qs.stringify({ username: 'admin', password: 'admin' })
      })
        .then((res) => res.json())
        .then((data) => {
          console.log(data)
        })
复制代码

 

 

fetch封装:

  1、src下新建utils/requset.js:

复制代码
import { fetch as fetchPolyfill } from 'whatwg-fetch'
import qs from 'qs'

const get = (options) => {
  let str = '',
    path = ''
  if (options.data) {
    for (let key in options.data) {
      str += `&${key}=${options.data[key]}`
    }
  }
  path = options.url + '?' + str.slice(1)
  return fetchPolyfill(path, {
    headers: {
      ...options.headers,
      'content-type': 'application-json'
    },
    credentials: 'include'
  }).then((res) => res.json())
}

const post = (options) => {
  return fetchPolyfill(options.url, {
    method: 'post',
    headers: {
      ...options.headers,
      'content-type': 'application/x-www-form-urlencoded'
    },
    credentials: 'include',
    body: qs.stringify(options.data)
  }).then((res) => res.json())
}

export default {
  get,
  post
}
View Code
复制代码

  2、引入和使用

复制代码
    import request from './utils/request'


    async componentDidMount() {
      let res = await request.get({
        url: '/users/login',
        data: {
          username: 'admin',
          password: 'admin'
        }
      })
      console.log(res, 'get')

      request
        .post({
          url: '/users/login',
          data: {
            username: 'admin',
            password: 'admin'
          }
        })
        .then((data) => {
          console.log(data, 'post')
        })
    }
复制代码

 

fetch的特点:

  1、返回promise

  2、留给开发者足够的操作空间,可以自定义返回的数据类型:json、text、blob、arrayBuffer...

  3、fetch处理成果后不是直接将结果返回,第一个then方法中返回一个未处理的结果集,在这里解析数据,第二个then方法中获取数据

  4、默认不会携带cookie,需要设置 credentials: 'include'

 

 

 

 

 

 

 

   

posted @   吴小明-  阅读(562)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结
点击右上角即可分享
微信分享提示