首页 文章

app.use和app.get与express.static有什么区别?

提问于
浏览
10

注意:结果我的问题不是middlware express.static(),而是app.use()和app.get()之间的区别 . 这个问题完美地回答了它(比明确的API文档更好!):

Difference between app.use and app.get in express.js

我理解app.use('/')和app.get('/')之间的区别在于后者仅向该 endpoints 提供HTTP GET请求,而前者提供对该 endpoints 的所有HTTP请求 .

我也理解express.static中间件提供从目录路径到 endpoints 的静态页面 .

我不遵循的原因是:

app.get('/', express.static(__dirname + '/public')

仅提供所请求的第一页,而不是所请求页面引用的任何ref =或src = link / script页面 . 例如,以下是两个响应简单index.html页面的摩根跟踪,该页面具有指向文件'style.css'的css链接

1)使用app.use('/')进行服务器请求跟踪

Server listening on 0.0.0.0:8080
GET / 200 6.258 ms - 444
GET /style.css 304 2.842 ms - -

2)使用app.get('/')跟踪服务器请求

Server listening on 0.0.0.0:8080
GET / 304 5.131 ms - -
GET /style.css 404 2.990 ms - 22

404 ???

即使浏览器向'/'发送了GET请求,app.get('/')也无法为css提供服务,但是app.use('/')成功了 .

我在app.get('/')或express.static中遗漏了哪些细节?

提前谢谢,PT

这是简单,简单的代码:

app.js:

var morgan = require('morgan'),
    express = require('express'),
    app = express(),
    server = require('http').Server(app);
app.use(morgan('dev'));

   // Uncomment .get or .use, but not both

   // this only serves index.html, not style.css when I nav to localhost:8080/
   //app.get('/', express.static(__dirname + '/pub'));

   // this serves both pages when I nav to localhost:8080/
   app.use('/', express.static(__dirname + '/pub'));

server.listen(8080);

这是html ...

的index.html

<!doctype html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>
</html>

路径:

/app.js
/pub/index.html
/pub/style.css

2 回答

  • 1

    app.get('/', handler) 是"add / to routing table, and when http GET request arrives call handler"

    app.use(middlevare) 是"add middlevare to the stack" .

    "middleware"是一个接受 (request, response, next) 的函数,下一个中间件由前一个显式调用next()

    express.static()返回中间件 - 特别是一个检查请求路径并将相应文件的内容流式传输到响应的函数 . 如果使用 app.get('/') 添加它,则永远不会调用非"/"路由

  • 6

    简短的回答是 app.use('/', express.static(__dirname + '/public')) 将匹配以 / 开头的任何路径 . 这意味着包括 /about/contact 之类的东西 . 但是, app.get('/', express.static(__dirname + '/public')) 将仅匹配特定路径 / . 因此,例如, /about/contact 将不包括在内 .

相关问题