从express / node.js应用程序

时间:2016-12-02 11:07:19

标签: express heroku

嗨,我是新手,最近开始了解节点。我在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的网址并非提供javascript文件,而是尝试为主页提供HTML。这表明您的应用程序中的路由存在问题,您需要查看该路由。这可能是因为您的server.js文件在发送index.html文件之前没有检查任何特定的URL。"

由于

1 个答案:

答案 0 :(得分: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中间件中设置静态文件夹,这样我就可以提供文件了。然后我将所有网址请求重定向到index.html

了解更多:express static

相关问题