【问题标题】:Serving static files from an express/node.js application从 express/node.js 应用程序提供静态文件
【发布时间】:2017-04-17 06:44:02
【问题描述】:

您好,我是新手,最近开始学习 node。我学习了关于 websockets (https://devcenter.heroku.com/articles/node-websockets) 的 Heroku 教程,并将其改编为我正在从事的特定项目。在示例代码中,有一个 index.html 文件,其中包含一些嵌入的 javascript。我将此脚本移到一个单独的文件中,并在 HTML 中引用它。在本地一切正常,但当我部署到 Heroko 时不起作用。我与 Heroku 非常乐于助人的团队聊天,他们告诉我,我的服务器端代码正在以 HTML 格式提供所有文件,我需要更改代码。他们给了我一些指示,我在几天内尝试了尽可能多的事情,但无济于事。最后,他们建议参加这个论坛作为解决问题的一种方式,因为这超出了他们的范围。提供 index.html 文件的现有代码如下:

const express = require('express');
const SocketServer = require('ws').Server;
const path = require('path');
const PORT = process.env.PORT || 3000;
const INDEX = path.join(__dirname, 'index.html');
const server = express()
.use((req, res) => res.sendFile(INDEX) )
.listen(PORT, () => console.log(Listening on ${ PORT }));

起初我编辑了这个以包含以下行:

app.use(express.static('public'))

但这不起作用。然后我修改如下,还是不行:

const INDEX = path.join(__dirname, 'index.html');
const JS = path.join(__dirname, 'client.js');

const server = express()
.use((req, res) => {
res.sendFile(INDEX);
res.sendFile(JS);

我查看了其他在我单独运行它们时有效的教程,但是当我尝试调整我上面的代码时它根本不起作用。如果有人能指出我正确的方向,我将不胜感激。

顺便说一句,这是 Heroku 告诉我的:

“为了进一步解释这个错误 Uncaught SyntaxError: Unexpected token http://thawing-journey-33085.herokuapp.com/client.js 的 URL 没有提供 javascript 文件,而是试图提供主页的 HTML。这表明你有一个问题您需要查看应用程序中的路由。这可能是因为您的 server.js 文件在发送 index.html 文件之前没有检查任何特定的 URL。"

谢谢

【问题讨论】:

    标签: express heroku


    【解决方案1】:

    我像这样提供我的静态文件:

    // define the folder that will be used for static assets
    app.use(Express.static(path.join(__dirname, '../public')));
    
    // handle every other route with index.html, which will contain
    // a script tag to your application's JavaScript file(s).
    app.get('*', function (request, response){
        response.sendFile(path.resolve(__dirname, '../public', 'index.html'));
    });
    

    这样我在 express.static 中间件中设置了静态文件夹,这样我就可以提供文件了。然后我将所有 url 请求重定向到 index.html

    了解更多:express static

    【讨论】:

    • 您好,感谢您的回复。我终于设法使用您的建议使其正常工作,但首先我必须重写我的代码以删除导致我出现问题的 javascript 6 语法。如果有人感兴趣,工作代码如下: app.use('/',express.static(__dirname)); app.get('/',function(req,res){ res.sendFile(INDEX); }) var server= app.listen(PORT,function(){ console.log("监听端口:"+ PORT) ; })
    猜你喜欢
    • 2016-10-26
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    相关资源
    最近更新 更多