NodeJS Express sendFile,包括外部JS文件

NodeJS Express sendFile that includes external JS files

本文关键字:JS 文件 包括外 Express sendFile NodeJS      更新时间:2023-09-26

所以,我有一个这样的文件结构:

App
 client
   index.html
   App.js
 server
   node_modules
   package.json
   server.js

server.js是由节点运行的服务器文件,它提供index.html

var app = require('express')();
var http = require('http').Server(app);

app.get('/', function(req, res){
   res.sendFile("client/index.html",{ root: '../' });
});


http.listen(3000, function(){
  console.log('Server is listening on port 3000');
});

因此,index.html在它的头中包含了App.js,就像你通常使用一样

        <script type="text/javascript" src="App.js"></script>

问题是,当我连接时,App.js永远不会被找到和包含。给出404。我该怎么修?

这个解决了我的问题。你可以看看这个。

var express = require('express');
var app = express();
app.use('/js', express.static(__dirname + '/public/js'));

因此,我的app.js可以通过->访问http://localhost:3000/js/app.js

当浏览器中请求http://127.0.0.1:3000时,服务器似乎什么都不做,只发送client/index.html。实际上,当浏览器收到index.html时,它会向http://127.0.0.1:3000/App.js发送另一个请求。但是您的服务器无法回答该请求。它只能处理对索引的请求。如果你想要一个静态服务器,请在Github上查看serve-static:https://github.com/expressjs/serve-static或者,您可以像对index.html所做的那样,为使用app.js的应用程序编写另一条路由。

查看您需要使用路径访问的服务器文件夹结构/client/App.js,而不仅仅是App.js

所以你的脚本标签看起来像

<script type="text/javascript" src="./client/App.js"></script>