简体   繁体   English

尝试提供静态 JS 文件 Node.js,Err 404

[英]Trying to serve static JS files Node.js, Err 404

I am trying to set up a simple node.js server to do some basic Socket.io work but when I try to serve my Static JS files I get this error:我正在尝试设置一个简单的 node.js 服务器来执行一些基本的 Socket.io 工作,但是当我尝试提供静态 JS 文件时,出现此错误:

GET https://somewebsitewithfiles.website net::ERR_ABORTED 404获取https://somewebsitewithfiles.website net::ERR_ABORTED 404

Here is my server and local code:这是我的服务器和本地代码:

Server:服务器:

var express = require('express');  
var app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;


app.get('/', (req, res) => {
  res.sendFile(__dirname + '/HTML/index.html');
});
app.use(express.static('Static'))

http.listen(port, () => {
  console.log(`Socket.IO server running at http://localhost:${port}/`);
})

Local:当地的:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script src="/Static/User.js"></script>
  
</body>
</html>

As you can see I have used the express static file command witch doesnt seem to be working .如您所见,我使用了快速静态文件命令女巫似乎不起作用。 My file system consists of my project folder and inside that is my Server JS file.我的文件系统由我的项目文件夹组成,里面是我的 Server JS 文件。 There is also folder in there called "Static" that has has my static files and a folder called HTML that has my index.html那里还有一个名为“Static”的文件夹,其中包含我的静态文件和一个名为 HTML 的文件夹,其中包含我的 index.html

any help appreciated.任何帮助表示赞赏。 Thanks谢谢

app.use(express.static('Static')) try putting this line above your '/' route app.use(express.static('Static')) 尝试将此行放在您的 '/' 路线上方

code:代码:

var express = require('express');  
var app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;

app.use(express.static('Static'))
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/HTML/index.html');
});


http.listen(port, () => {
  console.log(`Socket.IO server running at http://localhost:${port}/`);
})

Edit:编辑:

<script src="/Static/User.js"></script>

You dont have to mention the 'static' in the src path.您不必在 src 路径中提及“静态”。

Correct way:正确做法:

<script src="/User.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM