node.js - 使用 restify 提供静态文件

标签 node.js restify

我正在学习使用 Node.js。目前,我的文件夹结构如下所示:

index.html
server.js
client
  index.html
  subs
    index.html
    page.html
res
  css
    style.css
  img
    profile.png
  js
    page.js
    jquery.min.js

server.js 是我的网络服务器代码。我使用 node server.js 从命令行运行它。该文件的内容是:

var restify = require('restify');

var server = restify.createServer({
    name: 'Test App',
    version: '1.0.0'
});

server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());

server.get('/echo/:name', function (req, res, next) {
    res.send(req.params);
    return next();
});

server.listen(2000, function () {
    console.log('%s running on %s', server.name, server.url);
});

如您所见,此服务器依赖于 RESTIFY。有人告诉我必须使用 RESTIFY。但是,我不知道如何提供静态文件。例如,如何在我的应用程序中提供 *.html、*.css、*.png 和 *.js 文件?

谢谢!

最佳答案

来自 documentation :

server.get(/\/docs\/public\/?.*/, restify.plugins.serveStatic({
  directory: './public'
}));

但这会搜索 ./public/docs/public/ 目录中的文件。
如果您不想将请求路径附加到它,请使用 appendRequestPath: false 选项。

我更喜欢使用 __dirname关键在这里:

server.get(/\/public\/?.*/, restify.plugins.serveStatic({
    directory: __dirname 
}));

__dirname的值等于脚本文件目录路径,假设也是一个文件夹,这里是public目录。

现在我们将所有 /public/.* url 映射到 ./public/ 目录。


现在也存在serveStaticFiles插件:

server.get('/public/*', // don't forget the `/*`
     restify.plugins.serveStaticFiles('./doc/v1')
); // GET /public/index.html -> ./doc/v1/index.html file

关于node.js - 使用 restify 提供静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19281654/

相关文章:

javascript - Nodejs异步调用,如何处理一个url上的多个请求

javascript - 如何对需要其他模块的 Node.js 模块进行单元测试以及如何模拟全局 require 函数?

node.js - 使用 SinonJs 和 Mocha 测试包含 Promise 代码块的 Restify 路由处理程序

json - Node.js Restify - 简单服务

javascript - PassportJS 重定向循环

javascript - 使用node.js异步系列插入错误

node.js - 在 Heroku Express/Node 应用程序上使用 Cloudcube Addon 时无法连接到 S3

node.js - npm update 无法更改版本

node.js - 使用 mocha 测试二进制文件上传

javascript - MySQL NodeJS 错误 : Cannot enqueue Query after invoking quit using transactions