Html 浏览网站http://localhost 使用node.js代替文件://

Html 浏览网站http://localhost 使用node.js代替文件://,html,node.js,server,Html,Node.js,Server,我正在学习使用node.js 从file:///C:/.../myfolder/index.html 我的jquery和引导文件位于目录myfolder/css/和myfolder/js中 但是当我运行node index.js并转到localhost:3000时,找不到这些css和js文件 这是我的index.html文件中的内容: <link href="/css/bootstrap.min.css" rel="stylesheet"> <script src="/js

我正在学习使用node.js

file:///C:/.../myfolder/index.html
我的jquery和引导文件位于目录
myfolder/css/
myfolder/js

但是当我运行
node index.js
并转到
localhost:3000
时,找不到这些css和js文件

这是我的index.html文件中的内容:

 <link href="/css/bootstrap.min.css" rel="stylesheet">
 <script src="/js/bootstrap.min.js"></script>
 <script src="/js/jquery.js"></script>
 <script src="/socket.io/socket.io.js"></script>


nodejs中有我应该存储这些文件的文件夹吗?或者我必须在index.js中添加一些代码来导入所有css和js文件吗?

您的本地主机从您机器上的特定目录开始。如果使用Xampp,则必须将所有服务器文件放在C:\Xampp\htdocs\中,以便通过本地主机URL访问这些文件。其他一些服务器使用名为“www”的文件夹


找到服务器根路径并将文件放在那里。或者创建从服务器根目录到文件的符号链接。

是否需要路径模块

var path = require('path');
最好创建一个
public
目录来存储文件

public/index.html
public/css/style.css
public/js/scripts.js

您只需按照Express.js的快速入门说明操作即可:

然后浏览到
http://localhost:3000
进行测试

您可以使用Atom文本编辑器或括号,将文件放在
public
文件夹下并引用它们


默认情况下,Express使用名为Jade的模板引擎。您可以在这里查看以下内容:


祝你好运

无法访问localhost:3000/folder/file的原因是localhost:port只是一个虚拟端口。没有名为localhost:3000/css/或localhost:3000/js的目录

要解决这个问题,您需要使用express模块来配置根目录,从该根目录为静态资产提供服务

基本上,您需要添加以下代码:

var express=require('express');
var app=express();
var path=require('path');    
app.use(express.static(path.join(__dirname,'public')));
静态文件目录将是currentWorkingDirectory/public/,其中包含所有资产

在代码中,要链接任何源文件

href='/fileName.extention'

以下是文档链接

最接近的答案!在浏览了express文档之后,我发现通过添加行app.use(express.static(uu dirname+/public));当我的css和js文件夹位于公用文件夹中时,它可以工作。