2016-12-02 135 views
1

嗨,我是一个新手,最近开始了解节点。我在websockets上使用了Heroku教程(https://devcenter.heroku.com/articles/node-websockets),并将其改编为我正在开发的特定项目。在示例代码中,有一个index.html文件带有一些嵌入式JavaScript。我将这个脚本移出一个单独的文件并在HTML中引用它。一切工作正常本地,但不工作时,我部署到Heroko。我与Heroku非常有帮助的团队聊天,他告诉我我的服务器端代码将所有文件作为HTML提供,我需要更改代码。他们给了我一些指示,我尽可能多地尝试了几天,但无济于事。最后,他们建议来这个论坛作为解决问题的一种方式,因为它超出了他们的范围。这提供了index.html文件中的现有代码如下:从express/node.js应用程序提供静态文件

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告诉我:

“来解释远一点此错误未捕获的SyntaxError:意外的标记<是因为http://thawing-journey-33085.herokuapp.com/client.js的网址是不是服JavaScript文件而是试图服务这表明你的应用程序中有一个你需要查看的路由问题,这可能是因为你的server.js文件在发送index.html文件之前没有检查任何特定的URL。 “

感谢

回答

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

+0

嗨感谢您的回应。我终于设法使用你的建议,但首先我必须重写我的代码,以删除导致我的问题的JavaScript 6语法。如果有人感兴趣,工作代码如下:app.use('/',express.static(__ dirname)); (PORT,function(){ console.log(“Listening on port()”)在这个函数中, :“+ PORT); }) – LankyDonkey

+0

很高兴帮助!你能回答正确的答案吗?谢谢 – sendra

相关问题