react + axios

Installation: npm install axios --save-dev;

Creating server.js the src file

import axios from 'axios'
import qs from 'qs'
import { resolve } from 'dns';
let http={
    post:'',
    get:''
}
//请求前拦截
   axios.interceptors.request.use(function (config{
      return config;
   }function (error{
      return Promise.reject(error);
  );
// back to intercept data requests
axios.interceptors.response.use(function (response{
    return response;
  }function (error{
    return Promise.reject(error);
  });
http.post=function(api,data){
    let params=qs.stringify(data);
    return new Promise((reaolve,reject)=>{
        axios.post(api,params).then((res)=>{
            resolve(res)
        })
    })
}
http.get=function(api,data){
    let params=qs.stringify(data);
    return new Promise((reaolve,reject)=>{
        axios.post(api,params).then((res)=>{
            resolve(res)
        })
    })
}
export default http

  Introduced can be used in the assembly

import http from './server'

 proxy solve cross-domain

devserver: { 
    Proxy: { 
      '/ API': { 
        target: 'http://www.baidu.com/', 
        pathRewrite: { '^ / API': ''}, 
        changeOrigin: to true, if the domain name is the target // , the required parameters, 
        Secure: to false, // support https protocol agent provided 
      }, 
      '/ API2': { 
          ..... 
      } 
    } 
  }

  Parameter Description

1、/api

Capture flag API, if this string API, then began to match agents, 
such as API request /api/users, the request will be proxied  http://www.baidu.com/api/users  .

 2、target

API proxy address is the need to address cross-domain API. 
The address can be a domain name, such as: http://www.baidu.com
may also be an IP address: http://127.0.0.1:3000
If the domain name is a need to add additional parameters changeOrigin: true, otherwise it will fail agent.

3, Pthriawrite

Rewrite the path, that will modify the API path to the final request. 
For example, API path access: /api/users
Settings pathRewrite: {'^/api' : ''},, the
path to the final proxy access: http://www.baidu.com/users
the purpose is to give the proxy parameter name, while accessing the naming deleted.

4, changeOrigin: This parameter allows the target parameter is a domain name

5、secure:

secure: falseDo not check the security issues.
After setting, you can accept running on HTTPS, you can use the back-end server certificate is invalid

Guess you like

Origin www.cnblogs.com/shui1993/p/10955395.html