Javascript JS 文件得到一个 net::ERR_ABORTED 404 (Not Found)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/54173476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:12:43  来源:igfitidea点击:

JS file gets a net::ERR_ABORTED 404 (Not Found)

javascriptsockets

提问by EricTalv

I am trying to create a simple Io-web-chat. I recently wanted to seperate my <script>inside my html file to an external js file.

我正在尝试创建一个简单的 Io-web-chat。我最近想将我的<script>内部 html 文件分离到外部 js 文件。

this is my very simple folder structure:

这是我非常简单的文件夹结构:

Chat
|-- index.html
|-- index.js
`-- server.js

Relevant part of html file:

html文件的相关部分:

<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script src="index.js"></script>
</body>
</html>

Relevant part of index.js file:

index.js 文件的相关部分:

$(function() {

  //Initialize variables
  var $messageArea = $('#messages');
  var $InputMessage = $('#InputMessage');
  var $InputName = $('#InputName');

  //Initialize Socket
  var socket = io();

  //Send server Your message
  socket.emit('chat message', $InputMessage.val());

});

Relevant part of server.js file:

server.js 文件的相关部分:

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

I also tried putting my files in this public type structure that they have on the socket.io examples:

我还尝试将我的文件放在 socket.io 示例中的这种公共类型结构中:

Chat
|-- Public
|   |-- index.html
|   `-- index.js
`-- server.js

in that case I changed: src="/index.js"in html added /public/index.htmlinto the server.js file But no luck.

在那种情况下我改变了: src="/index.js"在 html 中添加/public/index.html到 server.js 文件但没有运气。

This is all running in localhost. What am I doing wrong here?

这一切都在本地主机中运行。我在这里做错了什么?

回答by MadWard

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

正如评论中提到的:您需要一种将静态文件发送到客户端的方法。这可以通过像 Nginx 这样的反向代理来实现,或者简单地使用express.static()

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it staticfor the example. Once it's done, add this line in your server code:

将所有“静态”(css、js、图像)文件放在一个专用于它的文件夹中,与放置“视图”(在您的情况下为 html 文件)的位置不同。我会以它static为例。完成后,在您的服务器代码中添加以下行:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

这将通过 /static 路由有效地为“静态”文件夹中的每个文件提供服务。

Querying your index.js file in the client thus becomes:

在客户端查询你的 index.js 文件就变成了:

<script src="static/index.js"></script>