Encapsulation of fetch request

  1. First create a utils folder in the src folder under the react project, and then create a new index.js file in the utils folder

Write code in index.js

const querystring = require("querystring");
export function httpGet (url) {
    
    
  const result = fetch(url)
  return result;
}
export function httpPost(url, params) {
    
    
  const result = fetch(url, {
    
    
    method: "POST",
    headers: {
    
    
      "Content-type": "application/x-www-form-urlencoded",
      "Accept":"application/json,text/plain,*/*"
    },
    body: querystring.stringify(params)
  })
  return result
}
  1. Then you need to create a new folder in src and write index.js and api.js to the api folder.
    2.1 How to write in index.js
import {
    
      httpGet, httpPost } from '../utils/index'
import base from './base'
const api = {
    
    
  getChengpin () {
    
    
    return httpGet(base.ownUrl + base.chengpin)
  },
  getLogin(params) {
    
    
    return httpPost(base.ownUrl + base.login, params)
  }
}
export default api

2.2 Writing method in base.js (configuration file)

const base = {
    
    
  ownUrl: "http://iwenwiki.com",
  chengpin: "/api/blueberrypai/getChengpinInfo.php",
  login: '/api/blueberryapi/login.php'
}
export default base

end of article

Guess you like

Origin blog.csdn.net/weixin_45664217/article/details/123026434