节点js express应用提供静态文件 [英] node js express app serve static files

查看:43
本文介绍了节点js express应用提供静态文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提供我的静态文件"web.html"和"mobile.html",但是仅当用户从网络/移动设备连接时才发送它们.

I want to serve my static files "web.html" and "mobile.html", but send them only if the user is connected from the web/mobile.

我认为这是执行此操作的代码:

i thought that this the code that does this:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/public', {index: false}));

app.get('/', function (req, res) {
console.log("user connected");

if (req.headers['user-agent'].match('mobile')) {

    res.sendFile(__dirname + '/public/mobile.html');

} else {

    res.sendFile(__dirname + '/public/web.html');
}
});

,但是此代码不起作用.根据我的理解,express.static仅在请求'/'时才提供index.html.请求'/'时,有没有一种方法可以提供特定文件?

but this code doesn't work. from what i understood the express.static will only serve index.html when requesting '/'. is there a way to serve a specific file when requesting '/' ?

谢谢!

推荐答案

<script src="/scripts/script.js"></script>

在索引文件或HTML文件中使用以上行.

Use the above line in the index file or the HTML file.

var app=express();
app.use(express.static(__dirname + '/assets'));

在app.js或节点js应用程序的起点中使用它.在根级别创建资产文件夹.在素材资源文件夹中有子文件夹:图片,CSS和脚本

Use this in the app.js or the starting point of your node js application. Create an assets folder at the root level. Inside assets folder there are sub folders : Images, CSS and Scripts

这篇关于节点js express应用提供静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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