superagent -- react 域名管理

前端之家收集整理的这篇文章主要介绍了superagent -- react 域名管理前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

因为react是一个mvvm的架构,因此他没有自带的ajax模块,然而这就给我们带来更多灵活的使用方法,

今天就来介绍一下react搭配superagent以及promise的交互方式

首先我们安装几个包

  1. npm install ramda --save
  2. npm install superagent --save
  3. npm install bluebird --save
  4. npm install superagent-bluebird-promise --save

接下来做一个domain.js域名管理文件

  1. import R from 'ramda';
  2. import request from 'superagent-bluebird-promise';
  3. import postRequest from 'superagent';
  4.  
  5. var env = 'dev';
  6.  
  7. const domainEnv = {
  8. 'localhost': 'local',//本地域名
  9. 'myDomain': 'prepro'//线上域名
  10. };
  11.  
  12. const apiHost = {
  13. 'local': 'http://127.0.0.1:8964',//注意这里不要漏掉{http://}
  14. 'prepro': ''
  15. };
  16.  
  17. const hostName = window.location.hostname;
  18.  
  19. if (R.has(hostName,domainEnv)) {
  20. env = domainEnv[hostName]; //获取当前域名
  21. }
  22.  
  23. const APIROOT = apiHost[env];//切换本地与线上的域名
  24.  
  25. const URL_OPTIONS = { //请求参数
  26. post: {
  27. method: 'post',headers: {'Content-Type': 'application/json'},data: {},dataType: 'json',timeout: 30000
  28. },get: {
  29. method: 'get',timeout: 30000
  30. }
  31. };
  32.  
  33. const GET_INFO = (relatieURL,fetchCallback) => {
  34. var url = APIROOT + relatieURL;
  35. url = encodeURI(url);
  36. return request.get(url)
  37. .then(res => {
  38. fetchCallback(res.body,null)
  39. },error =>{
  40. fetchCallback(null,error)
  41. })
  42. };
  43. const PUT_INFO = (relatieURL,params,cb) => {
  44. var url = APIROOT + relatieURL;
  45. url = encodeURI(url);
  46. postRequest
  47. .post(url)
  48. .send(params)
  49. .set('Accept','application/json')
  50. .end(function(err,res) {
  51. if (err) {
  52. cb(err,res);
  53. } else if (res.statusNo != 200) {
  54. cb(null,res.body);
  55. } else {
  56. cb(null,res.body);
  57. }
  58. });
  59. };
  60. module.exports = { APIROOT,URL_OPTIONS,GET_INFO,PUT_INFO };

这个文件封装了domain的管理以及post与get两种请求方式

然后从业务逻辑上来调用封装好的请求方式

举个栗子... 我创建一个loginApi.js的模块

  1. import { GET_INFO,PUT_INFO } from './domain.js';
  2.  
  3. export function login (params,cb){
  4. return GET_INFO('/login' + params.loginForm,cb);
  5. }
  6.  
  7. export function logout (params,cb){
  8. return GET_INFO('logout/',cb)
  9. }

那么接下来我们就可以在view层直接调用啦,看下面

  1. import { login,logout } from 'loginApi.js';
  2.  
  3. export default class News extends Component {
  4.  
  5. constructor(props) {
  6. super(props)
  7. login({},(res)=>{
  8.  
  9. });
  10. }
  11.  
  12. render(){
  13. return (
  14. <div></div>
  15. )
  16. }
  17. }

完事啦,这样的话就把 功能 - 业务 - 展示都剥离开了 而且实现起来也非常的方便

猜你在找的React相关文章