[英]NodeJS Express sendFile that includes external JS files
So, I have a file structure like this: 所以,我有一个像这样的文件结构:
App
client
index.html
App.js
server
node_modules
package.json
server.js
the server.js is the server file ran by node, it serves up the index.html 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');
});
So the index.html includes the App.js in it's head, like you normally would 因此index.html就像通常那样在其头部包含App.js
<script type="text/javascript" src="App.js"></script>
The problem is, that App.js is never found and included when I connect. 问题是,当我连接时,永远找不到并包含App.js。 Gives a 404. How could I fix it?
给出404。我该如何解决?
Your server doesn't seem to do anything but sending client/index.html
when http://127.0.0.1:3000
is requested in a browser. 当在浏览器中请求
http://127.0.0.1:3000
时,您的服务器似乎什么也不做,只是发送client/index.html
。 So what actually happens, when the browser received the index.html, it sends another request to http://127.0.0.1:3000/App.js
. 因此,实际上发生了什么,当浏览器接收到index.html时,它将向
http://127.0.0.1:3000/App.js
发送另一个请求。 But your Server can't answere that request. 但是您的服务器无法回答该请求。 It can only anwere requests for the index.
它只能对索引的要求。 If you want a static server check out serve-static on Github: https://github.com/expressjs/serve-static Or you could write another route for you app anwering with the App.js as you did for the
index.html
. 如果您想使用静态服务器,请在Github上查看serve-static: https : //github.com/expressjs/serve-static,或者您可以像为
index.html
所做的那样为App.js占用应用程序编写另一条路由。
This one solved mine. 这个解决了我的问题。 You can check this out.
您可以检查一下。
var express = require('express');
var app = express();
app.use('/js', express.static(__dirname + '/public/js'));
Thus, my app.js can be accessed via -> http://localhost:3000/js/app.js 因此,我的app.js可以通过-> http:// localhost:3000 / js / app.js进行访问
looking at your server folder structure you need to access using the path ./client/App.js, instead of only App.js 查看您的服务器文件夹结构,您需要使用路径./client/App.js进行访问,而不仅仅是App.js
So your script tag will look like, 所以您的脚本标签看起来像
<script type="text/javascript" src="./client/App.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.