如何使用 historyApiFallback 和代理远程 api 请求来设置 webpack 开发服务器? [英] How to setup a webpack dev server using both historyApiFallback and proxying remote api requests?

查看:26
本文介绍了如何使用 historyApiFallback 和代理远程 api 请求来设置 webpack 开发服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 react-router 的 react 应用程序,所以它使用了 HTML5 历史 API,我已经尝试将 historyApiFallback 设置为 true 为 404 路径提供相同的 index.html 而不是返回 HTTP 响应.

I have a react application which uses react-router, so it's making use of HTML5 history API, I've tried historyApiFallback set to true to serve 404 paths serving the same index.html instead of returning the HTTP response.

那个单页应用程序向远程 API 服务器发出一些请求,这就是为什么我还需要将一些请求代理到我在开发时也在运行的快速服务器.Web React 应用程序在端口 3000 上提供服务,API 在端口 3001 上运行.

That single page application does some requests to a remote API server, that's why I also need to proxy some requests to the express server I'm also running while developing. Web react application is served on port 3000 and API runs on port 3001.

所以我试过了:

devServer:{
    contentBase: 'src/www',  //Relative directory for base of server
    devtool: 'eval',
    hot: true,        //Live-reload
    inline: true,
    port: 3000,        //Port Number
    host: 'localhost', //Change to '0.0.0.0' for external facing server
    historyApiFallback: true,
    proxy: {
      '^\/users|sitters|bookings': {
        target: 'http://127.0.0.1:3001',
        rewrite: function(req) {
          req.url = req.url.replace(/^\/api/, '');
        }
      }
    }
  },
  devtool: 'eval',
  output: {
    path: buildPath,    //Path of output file
    filename: 'app.js'
  },

因此,如果请求的路径以 /users/sitters/bookings 开头,我想要的是访问远程 api 服务器但否则请使用 historyApiFallback(提供 index.html).

So I what I want is hitting the remote api server if the request's path starts with either /users or /sitters or /bookings but go for historyApiFallback (serve index.html) otherwise.

当然,现在 historyApiFallback 始终为 HTML 文件提供服务,但我还需要代理正常工作.

Of course right now historyApiFallback works always serving the HTML file but I'd also need the proxy to be working.

推荐答案

免责声明.这个答案可能已经过时

在 Express 中间件中,堆栈顺序很重要.

应该先在 webpack config 中设置代理,而不是 historyApiFallback,它应该是这样的:

  devServer:{
    contentBase: 'src/www',  //Relative directory for base of server
    devtool: 'eval',
    hot: true,        //Live-reload
    inline: true,
    port: 3000,        //Port Number
    host: 'localhost', //Change to '0.0.0.0' for external facing server
    proxy: {
      '^\/users|sitters|bookings': {
        target: 'http://127.0.0.1:3001',
        rewrite: function(req) {
          req.url = req.url.replace(/^\/api/, '');
        }
      }
    },
    historyApiFallback: true
  },

当然,代理可以根据应用程序的需要更改为任何模式或正则表达式.就我而言,这正是我所需要的.

So of course proxy can be changed to any pattern or regex as an application needs it. In my case that's what I needed.

这篇关于如何使用 historyApiFallback 和代理远程 api 请求来设置 webpack 开发服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆