javascript - 使用express的静态中间件时没有任何反应

标签 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);

通常应用程序应该为我提供公共(public)目录中的任何内容。我将图像放在公共(public)文件夹中(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

最佳答案

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

关于javascript - 使用express的静态中间件时没有任何反应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50178434/

相关文章:

javascript - document.readyState "Access not allowed"与 Applescript +Javascript 等待页面加载

node.js - process.stdout.write/process.stderr.write 猴子补丁适用于子进程,但不适用于父进程

node.js - socket.io - 第一次工作,而不是第二次

javascript - res.clearCookie 函数不会删除 cookie

javascript - 在 Angular Controller 抛出的异常中获取原始文件名+行号?

javascript - 如何使用 getelementbyid/tag/name 将 id 定位到 div 内的图像?

javascript - 如何在 Chrome 中禁用 ES6 功能

node.js - 如何在当前更新的 mongodb 网站上获取标准 URI 连接字符串(不带 srv)?

javascript - 使用 Node 在内存中处理大型 JSON 数据集

javascript - 将应用程序部署到 Heroku,ENV 变量不起作用