webpack中使用WebpackDevServer实现请求转发

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>html template</title>
  </head>
  <body>
    <div id='root'></div>
  </body>
</html>

index.js

import React, {Component} from 'react';
import ReactDom from 'react-dom';
import axios from 'axios';
class App extends Component{   render() {     
return (       <div>hello world</div>     )   }   componentDidMount(){     axios       .get('/react/api/header.json')       .then((res)=>{         console.log(res);       })   } } ReactDom.render(<App/>, document.getElementById('root'));

使用 npm run dev ("webpack-dev-server --config ./build/webpack.common.js")打包进行开发。这个时候这个接口会报错。因为localhost下面没有这个接口,那我们去请求线上的(在对方服务器允许我们跨域的时候)。我们看webpack怎么配置https://webpack.js.org/configuration/dev-server#devserverproxy。可以看到dev下面有个devServer:proxy的配置项。通过这个配置项就可以很方便进行本地接口的调试

module.exports = {
  devServer: {
    contentBase:'./dist',
    open:true,
    hot: true,
    proxy: {
      '/react/api': 'http://www.xxx.com'
    }
  }
}

配置一个proxy。意思是在/react/api下面的接口走的都是http://www.xxx.com的/react/api接口。

但是如果这个线上的接口没有好,需要用假数据。后端给了一个demo.json的临时数据用,可以这么配置
module.exports = {
  devServer: {
    contentBase:'./dist',
    open:true,
    hot: true,
    proxy: {
      '/react/api': {
        target: 'http://www.xxx.com',
        pathRewrite: {
          'header.json': 'demo.json'
        }
      }
    }
  }
}

这个的意思是,如果用户请求/react/api下的接口时,首先会到www.xxx.com下面去拿数据,但拿数据的时候他还有些规则,如果拿的是header.json的数据,其实不是拿header.json下的数据,而是demo.json的数据。

 

最后这个proxy是devServer的proxy,这就意味着只有在开发环境下,我们对proxy的配置才会生效,因为只有开发环境下才会使用。如果这个网址是https的时候,需要加个配置支持,secure:false
module.exports = {
  devServer: {
    contentBase:'./dist',
    open:true,
    hot: true,
    proxy: {
      '/react/api': {
        target: 'https://www.xxx.com',
        secure: false
      }
    }
  }
}

这里我们只讲了一个路径,/react/api,如果有多个路径怎么办呢,可以放在context里面去管理

module.exports = {
  devServer: {
    proxy: [{
      context: ['/auth', '/api'],
      target: 'http://localhost:3000',
    }]
  }
};

他的意思是你访问 /auth 或者 /api 这个路径的时候,都会代理到localhost:3000这个域名下。

 

除了这些,还有一些其他的配置。https://github.com/chimurai/http-proxy-middleware#options
 

 

posted @ 2019-05-18 12:05  wzndkj  阅读(406)  评论(0编辑  收藏  举报