react项目请求数据的fetch的使用

准备三个文件(封装请求函数),然后测试一下,能不能调用数据

react项目请求数据的fetch的使用

第一个文件  request.js

import 'whatwg-fetch';

/**
* Parses the JSON returned by a network request
*
* @param {object} response A response from a network request
*
* @return {object} The parsed JSON from the request
*/
function parseJSON(response) {
if (response.status === 204 || response.status === 205) {
return null;
}
return response.json();
} /**
* Checks if a network request came back fine, and throws an error if not
*
* @param {object} response A response from a network request
*
* @return {object|undefined} Returns either the response, or throws an error
*/
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
} const error = new Error(response.statusText);
error.response = response;
throw error;
} /**
* Requests a URL, returning a promise
*
* @param {string} url The URL we want to request
* @param {object} [options] The options we want to pass to "fetch"
*
* @return {object} The response data
*/
export default function request(url, options) {
return fetch(url, options)
.then(checkStatus)
.then(parseJSON);
}

第二个文件  jshNetwork.js

/**
* Created by 23hp on 2017/4/13.
* 基于Promise的网络请求库,包含GET POST请求,上传下载功能
* 使用方法:
* 先引入: import {get,post,...} from 本文件;
* · get请求: get("http://api.lolatc.com/v1",{id:2}).then(data=>{}).catch(error=>{});
* · post请求: post("http://api.lolatc.com/v1",{id:2}).then(data=>{}).catch(error=>{});
* then方法里的参数第一个是成功回调,第二个是失败回调,两个回调都是可选的
*/
import request from './request'; /**
* 发送get 请求
* @param url 路径 必填
* @param headers 请求头参数 可选
*/
export function get(url, headers = { 'Content-Type': 'application/json' }) {
return request(url, {
method: 'GET',
headers,
});
}
/**
* 发送POST请求
* @param url 路径 必填
* @param param 参数 可选
* @param headers 请求头参数 可选
*/
export function post(url, param, headers = { 'Content-Type': 'application/json' }) {
return request(url, {
method: 'POST',
headers,
body: JSON.stringify(param),
});
}

第三个文件   service.js

import { post } from './jshNetwork.js';

export function getProductList(getParam) {
const params = {
doctype: '51etm',
page_size: 5,
page: 1,
clttype: 'decoration',
isLogin: '2',
matgroup: '瓷砖',
stcode: '',
sales: 'desc'
};
const url = 'https://java-getway-stg.heyiit.com/java-getway/apigateway/api.do?api_path=/lola_cms_Interface/rc_manage/selectBy_Condition_and_TimatGeneral.do&flagForAddress=rc_cms';
return post(url, params);
}

第四个文件请求调用数据

import React, { Component } from 'react';
import 'antd-mobile/dist/antd-mobile.css';
import {getProductList} from "../utils/service";
import {Button} from "antd-mobile"; class qqq extends Component {
buttonRequest = () => {
getProductList().then((data)=>{
console.log("data",data);
});
}
render() {
return (
<div style={{ paddingTop:"200px" }}>
<Button type="primary" onClick={this.buttonRequest}>首页按钮</Button>
</div>
);
}
} export default qqq;

react项目请求数据的fetch的使用

这样,测试成功。

上一篇:iOS越狱程序开发


下一篇:基于 Koa平台Node.js开发的KoaHub.js获取/设置会话功能代码