首页 > webpack-dev-server 代理请求 api

webpack-dev-server 代理请求 api

在 开发 react 时,使用 webpack 开发,
在 请求 api 数据的 时候 ,遇到的 跨域的问题,
看到 webpack-dev-server 可以代理请求,

看到 官网的说明

proxy: {
  '/some/path*': {
    target: 'https://other-server.example.com',
    secure: false
  }
}

于是在自己 的 webpack 中 加入

var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');

new WebpackDevServer(webpack(config), {
  contentBase: './public',
  publicPath: config.output.publicPath,
  hot: true,
  
  proxy: {
    '/ShoppingGuideAPI/*': {
        target: 'http://api.mu.com',
        secure: false,
    }
  },
  historyApiFallback: true
}).listen(3000, 'localhost', function(err, result) {
  if (err) {
    console.log(err);
  }
  console.log('Listening at localhost:3000');
});

在 react 组件中 引入了 Fetch

import 'whatwg-fetch';

 // 组件渲染后获取外界数据
componentDidMount() {
    fetch(api)
        .then((response) => {
            return response.json();
        })
        .then((data) => {
            console.log(data);
            this.setState({
                data: data[0]['description'],
             
            });
   
            console.log(this.state.data);
        })
        .catch((ex) => {
            console.log(ex);
        });
}

最后在请求 数据的时候 返回的却是 404 结果


/ShoppingGuideAPI/* -> /ShoppingGuideAPI

大概这样就可以了,我用的另外一个vue的webpack项目,我看了下源码是基于http-proxy模块实现的。

/**
 * @param  {String} context '/api'
 * @param  {String} uri     'http://example.org/api/b/c/d.html'
 * @return {Boolean}
 */
function matchSingleStringPath(context, uri) {
    var path = getUrlPath(uri);
    return path.indexOf(context) === 0;
}
【热门文章】
【热门文章】