【问题标题】:Serve static index.html and API on same port在同一端口上提供静态 index.html 和 API
【发布时间】:2017-05-24 12:12:56
【问题描述】:

我使用 Node/Express 作为 API 代理服务器,想知道是否可以为所有 GET 路由呈现 HTML (index.html) 页面以及在同一个端口。我正在使用客户端路由(react-router)。

例如:

// Always return the main index.html, so react-router render the route in the client
app.get('*', (req, res) => {
  const html = renderHTML(req, res);
  res.send(html)
});

// Expose API
app.all('/api/*', (req, res, next) => {
    proxyRequest(...)
});

问题是在做 GET 请求时,第一个 app.get() 捕获它(例如:fetch('/api/accounts'))。

我需要能够向任何 API 端点路由(/ 除外)发出任何请求,并让客户端发送任何方法(GET、PUT、POST...)。

我可以将index.html 提供给所有客户端路由并且在同一端口上有 GET 端点吗?我可以为所有以/api/ 前缀的路由除了提供html吗?

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    如果您首先公开您的端点,然后提供您的 html,它应该可以完成这项工作。

    // Expose API
    api.all('/api/*', cb);
    
    // Serve HTML 
    api.get('*', cb);
    

    【讨论】:

    • 对不起,cb 是什么?
    • 回调/处理函数
    【解决方案2】:

    创建一个名为public的目录。

    将您的HTML 和支持文件放入其中。

    app.use(express.static(path.resolve('./public')));
    
    //Your API routes here
    

    express.static 将提供静态 HTML 文件,然后您可以添加路由语句。这将在同一个端口上工作。

    【讨论】:

    • express.static 如何提供 API?
    • 不,express.static 不会提供 API。您现有的陈述会做到这一点。这将在/ parth 上提供 index.html
    • 看来您可能没有完全理解我的问题。这是一个路由问题,而不是一个提供服务的静态文件。
    • 根据我的阅读,您希望提供 HTML 文件并在同一端口上拥有 API。这样就可以了。
    猜你喜欢
    • 2016-01-18
    • 2018-03-30
    • 2013-08-02
    • 2021-07-20
    • 2018-12-14
    • 1970-01-01
    • 2020-05-02
    • 2010-12-08
    • 2020-08-08
    相关资源
    最近更新 更多