nodejs / express包括本地js文件 [英] nodejs/express include local js file

查看:218
本文介绍了nodejs / express包括本地js文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我目前的资料夹结构

Here is my current folder structure

css
   app.css
js
  app.js
node-modules
index.html
node-server.js
package.json

节点服务器托管 index.html ,但我不知道如何获得 app.js app.css 文件。

The node-server is hosting index.html, but I can't figure out how to get the app.js and app.css files to get loaded.

code> index.html 加载它们:

index.html loads them with:

<script src="js/app.js"></script>
<link rel="stylesheet" type="text/css" href="css/app.css"/>

以下是错误讯息:

Failed to load resource: the server responded with a status of 404 (Not Found)
2http://localhost:3000/css/app.css Failed to load resource: the server 
responded with a status of 404 (Not Found)

我知道我需要加载模块或某物,只是不能弄清楚什么。

I know i need to require or load module or something, just can't figure out what.

感谢

推荐答案

原因
Node.Js不是自己的服务器静态内容,路由必须定义为通过Node提供静态内容。

Reason Node.Js does not server static content on it's own, routes has to defined for serving static content via Node.

解决方案(手动)

var express = require('express'),
    path = require('path'),
    app = express();

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

app.get('/css/app.css',function(req,res){
    res.sendFile(path.join(__dirname + '/css/app.css')); 
});

app.get('/js/app.js',function(req,res){
    res.sendFile(path.join(__dirname + '/js/app.js')); 
});

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

app.listen(8080);

更好的解决方案

目录结构:

public
 css
   app.css
 js
  app.js
 index.html

CODE:

var express = require('express'),
    path = require('path'),
    app = express();

// Express Middleware for serving static files
app.use(express.static(path.join(__dirname, 'public')));

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

app.listen(8080);

这篇关于nodejs / express包括本地js文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆