因为react是一个mvvm的架构,因此他没有自带的ajax模块,然而这就给我们带来更多灵活的使用方法,
今天就来介绍一下react搭配superagent以及promise的交互方式
首先我们安装几个包
- npm install ramda --save
- npm install superagent --save
- npm install bluebird --save
- npm install superagent-bluebird-promise --save
接下来做一个domain.js域名管理文件
- import R from 'ramda';
- import request from 'superagent-bluebird-promise';
- import postRequest from 'superagent';
- var env = 'dev';
- const domainEnv = {
- 'localhost': 'local',//本地域名
- 'myDomain': 'prepro'//线上域名
- };
- const apiHost = {
- 'local': 'http://127.0.0.1:8964',//注意这里不要漏掉{http://}
- 'prepro': ''
- };
- const hostName = window.location.hostname;
- if (R.has(hostName,domainEnv)) {
- env = domainEnv[hostName]; //获取当前域名
- }
- const APIROOT = apiHost[env];//切换本地与线上的域名
- const URL_OPTIONS = { //请求参数
- post: {
- method: 'post',headers: {'Content-Type': 'application/json'},data: {},dataType: 'json',timeout: 30000
- },get: {
- method: 'get',timeout: 30000
- }
- };
- const GET_INFO = (relatieURL,fetchCallback) => {
- var url = APIROOT + relatieURL;
- url = encodeURI(url);
- return request.get(url)
- .then(res => {
- fetchCallback(res.body,null)
- },error =>{
- fetchCallback(null,error)
- })
- };
- const PUT_INFO = (relatieURL,params,cb) => {
- var url = APIROOT + relatieURL;
- url = encodeURI(url);
- postRequest
- .post(url)
- .send(params)
- .set('Accept','application/json')
- .end(function(err,res) {
- if (err) {
- cb(err,res);
- } else if (res.statusNo != 200) {
- cb(null,res.body);
- } else {
- cb(null,res.body);
- }
- });
- };
- module.exports = { APIROOT,URL_OPTIONS,GET_INFO,PUT_INFO };
这个文件封装了domain的管理以及post与get两种请求方式
然后从业务逻辑上来调用封装好的请求方式
举个栗子... 我创建一个loginApi.js的模块
那么接下来我们就可以在view层直接调用啦,看下面
- import { login,logout } from 'loginApi.js';
- export default class News extends Component {
- constructor(props) {
- super(props)
- login({},(res)=>{
- });
- }
- render(){
- return (
- <div></div>
- )
- }
- }
完事啦,这样的话就把 功能 - 业务 - 展示都剥离开了 而且实现起来也非常的方便