【问题标题】:How to serve a static html file directly from server in React+Express?如何在 React+Express 中直接从服务器提供静态 html 文件?
【发布时间】:2019-10-11 11:02:51
【问题描述】:

我从网站构建器下载了一个漂亮的 html 页面,其中包含指向所需 css 和 js 的链接,并希望将其用作我的登录页面。我有一个完整的 React 应用程序,并希望将此下载的 html 文件作为 / 路由的登录页面。这样做的最佳方法是什么?

我已经查看了<div dangerouslySetInnerHTML>,如下例所示,但它导致页面加载缓慢。


export default class StaticContainer extends Component {
  state = {
    __html: "" // copy/paste html here
  }


  render() {
    return (
        <div dangerouslySetInnerHTML={this.state} />
    );
  }
}```

【问题讨论】:

  • 为什么不把下载的html转换成自己的组件呢?还是动态内容会发生变化?
  • 这与我上面粘贴的示例有何不同?
  • 这样做你不依赖 dangerouslySetInnerHTML 并且 React 的人并没有毫无理由地命名它,可能是他们正在用你提供的价值在幕后做一堆事情,从而导致缓慢大概。您是否尝试过创建一个新组件并检查结果?
  • 找到了解决方法并使用http-middleware-proxy发布了解决方案

标签: html reactjs express react-router


【解决方案1】:

通过使用http-proxy-middleware 将特定路径直接代理到服务器来解决此问题。有关更多信息,请参阅 React 文档中标题为 Configuring the proxy manually 的部分。

安装http-proxy-middleware。在 React 客户端应用程序中创建文件src/setupProxy.js,如下所示:

const proxy = require('http-proxy-middleware');

// Matches landing page at / alone
var landingPageFilter = function (pathname, req) {
    console.log(pathname);
    return pathname.match('^\/$') && req.method === 'GET';
};

module.exports = function (app) {
    // this is for APIs
    app.use(proxy('/api', { target: 'http://localhost:3001/' }));
    // this is for the landing page
    app.use(proxy(landingPageFilter, { target: 'http://localhost:3001/' }));
};

就我而言,我使用 Express 作为使用 express-generator 创建的服务器。在app.js 中处理了这些路由,如下所示:

app.use('/api/', indexRouter);

app.use("/", (req, res) => {
  res.status(200).sendFile(path.resolve(__dirname, "../public", "landing_page.html"));
});

landing_page.html 是我们希望在没有 React 的情况下提供的下载页面

编辑:这仅在开发中有效。对于 prod,您需要构建 React 页面并为它们提供服务。关注this tutorial,但要确保你有正确的路径来构建 React 页面。在教程中,它是client/build。根据您的目录结构可能会有所不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    • 2013-03-25
    • 2021-07-19
    • 2020-02-21
    相关资源
    最近更新 更多