使用express的静态中间件时没有任何事情发生

时间:2018-05-04 15:31:01

标签: javascript node.js express

我正在跟随一个在Evan Hann的 express in action 一书中使用express的静态中间件的例子。

这是我写的代码

var express = require('express');
var path = require('path');
var http = require('http');

var app = express();

// sets up the public path, using Node's path module
var publicPath = path.resolve(__dirname, "public");
app.use(express.static(publicPath));

app.use(function (req, res) {
    res.writeHead(200, { "Content-Type": "text/plain"});
    res.end("Look like you didn't find a static file.")
});

http.createServer(app).listen(3000);

通常,应用程序应该为我提供公共目录中的任何内容。我将图像放在公共文件夹(Twitter_32.png)中。但是当我导航到http://localhost:3000/时,一切都没有发生。

我错过了什么?

以下是package.json的内容:

{
  "name": "hello-world",
  "version": "1.0.0",
  "description": "hello world example using expressjs",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "hello",
    "world",
    "express"
  ],
  "author": "Sandro Agboka",
  "license": "ISC",
  "dependencies": {
    "eslint": "^4.19.1",
    "express": "^4.16.3",
    "morgan": "^1.9.0",
    "tslint": "^5.9.1",
    "typescript": "^2.8.3"
  }
}

这是我的项目目录结构

drwxr-xr-x   8 macbook staff   272 May  4 14:59 .
drwxr-xr-x   4 macbook staff   136 May  3 16:04 ..
-rw-r--r--   1 macbook staff  1155 May  3 17:48 app-old.js
-rw-r--r--   1 macbook staff   440 May  4 15:02 app.js
drwxr-xr-x 191 macbook staff  6494 May  3 17:40 node_modules
-rw-r--r--   1 macbook staff 53133 May  3 17:40 package-lock.json
-rw-r--r--   1 macbook staff   465 May  3 17:40 package.json
drwxr-xr-x   3 macbook staff   102 May  4 14:59 public

1 个答案:

答案 0 :(得分:1)

您需要导航到完整资源路径:http://localhost:3000/Twitter_32.png