学习节点 - Express公用文件夹不工作 [英] Learning Node - Express Public folder not working

查看:115
本文介绍了学习节点 - Express公用文件夹不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我是新来的节点,并试图学习如何使用 express 库。但是,我想知道的问题是为什么我的 / public 文件夹中的文件似乎不被用作静态内容。

So I'm new to node and trying to learn how to use the express library with it. However, the problem I'm trying to figure out is why the files in my /public folder do not seem to be served as static content.

这是我的代码:

var http = require('http');
var port = process.env.port || 1337;
var express = require('express');
var handlebars = require('express3-handlebars');
var path = require('path');

var application = express();

application.use(express.static(path.join(__dirname, 'public')));

application.engine('handlebars', handlebars({ defaultLayout: 'main' }));

application.get('/', function(req, res){
    res.render('index.handlebars', { someProp: 3 });
});

application.listen(port);

我的目录结构:

/
  - server.js (the above referenced file)
  / Views
    - index.handlebars
    / Layouts
      - main.handlebars
  / public
    - ServeMe.txt

我的理解是 application.use(express.static(path.join(__ dirname,'public')))); 应该配置服务器以响应该资源下的公用文件夹下的任何请求如果发现。我究竟做错了什么?有趣的是,配置handlebars作为视图引擎比将该公用文件夹工作的方式更容易= D

My understanding was that application.use(express.static(path.join(__dirname, 'public'))); was supposed to configure the server to respond to any request under the public folder with that resource if found. What am I doing wrong? Funnily enough, it was easier to configure handlebars as the view engine than to get this public folder working =D

编辑:我要请求的完整URL:
http:// localhost:1337 / public / serveme.txt

The full URL I am trying to request: http://localhost:1337/public/serveme.txt

我尝试过区分大小写这应该是一个非问题),这也没有奏效。

I've tried case sensitivity (which should be a non-issue), and that also did not work.

推荐答案


我要求的完整网址: http: /localhost:1337/public/serveme.txt

这是你的问题。您指定为静态内容的目录中的任何内容都可以直接从基本URL获得。您需要请求 http:// localhost:1337 / serveme.txt

That's your problem. Anything inside the directory you designate as static content is made available directly from the base URL. You need to request http://localhost:1337/serveme.txt instead.

如果您只想从 / public 提供静态文件,您可以传递一个字符串作为第一个参数:

If you want to only serve static files from /public you can pass a string as the first argument:

application.use("/public", express.static(path.join(__dirname, 'public')));

这篇关于学习节点 - Express公用文件夹不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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