静态文件
要提供静态文件,例如图像、CSS 文件和 JavaScript 文件,请使用 Express 中的 express.static
内置中间件函数。
函数签名是:
express.static(root, [options])
root
参数指定提供静态资产的根目录。有关 options
参数的更多信息,请参阅 express.static。
例如,使用以下代码在名为 public
的目录中提供图像、CSS 文件和 JavaScript 文件:
app.use(express.static('public'))
现在,您可以加载 public
目录中的文件:
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
Uz+1bjzz9zi6xnlDINCbW76B5BpUiBBmz4rXLN+oUAMhtXBGggJzHm7E5UGcJggzrfMuAFpBIi6Kq5tcu7d1mMIwTwOKw0Af4oP8/NwtnrZ8eSSG7M9LvXDMSZNKMVAP12jKhCoM/TbtUHBLLaYZ8Q==
l4YQtUS1CCv1vInz1wq+gBvMkgVAw7gwhwGptm+/kMVW54OnIlWn03pkGY44LXySXxvzQqy5T10+agbUJ9Sf0z7EYgcNf6POlkVxk9lLLscFxfyFiGwaN745Jfi9F1UNju+obUcnd77TAKo0HkQW7g==
app.use(express.static('public'))
app.use(express.static('files'))
FPUEZKb8QOZWziiMsLJNZe4/fKOBNvlxJ2SOPrEwIa8bRd5JZUTtrJeHd9resWOew2xSVmJk2RDj4j4hOUIFXKpEzU4ecqR3NhIdj6SCFlOa8UJCRomvWkm78LYUMx04Ssq58lsk4w0YbYvkgy0UQQ==
bVMDX/nKkOhYTR1J+W3FHx425ue9D6ADWvSOQ24I0SA2H+X5IQGSTMuiPaVjF0f/t4lQ9FFfy97r+0/KxF2w/N954xKTtSLK5Cn7m3Yh3+bmY8R518N4kbvDBCGqqkX2suJxuyYnAYPnNQe0BRHUWzBwPIByZZLJBrQb74VmSQvH48zM/aVf7M+0f/lKQ4mQSLwjC/H2H71fZIE2Bnflmw==
cQXUlHuTff8nnu85sIjxeO/+7xaCfzKh3UT8SfNHmsBeO1Rm+W3Gbt8qgkBbcgAvGjDL+8kd3JaMX8RekvXpWnHet2YUoH+c0zbU7qSG5jdP1HTZ27uVz3N/RLiLtZ2zoiiybv2g+O9Be8TTqdOjttcZa9oT/hY+Lw8RsJBZ+nL5vZ/lWAr+SFIikZEBSuUpq4lhcv3b9YTv6wEOKmA4A2Fni4iOUjMt4tDeX5SAD0huRn0mmGJ6r69NBuhp3PbH4Q9kSy+LJKv73bDZnDCs4aVi6VHbB0zOMb3X2UZZF2E0CmYKtok4oWMKUdHGHxv4
app.use('/static', express.static('public'))
PEOp675/oa4/jamsvM5IArf95aJv+Y+v6skjEC9XpDj1d8Pd8bVAj10EYlP+sBVvqpCbx2FVHR2xRSik7FKDpH5qb5oqlUGx1TUZ3sqFZLk09/0jMDTe/suBl5LLZSFdWLwTbozpp643AbifDTEk6w==
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
hQn5632fyss+Y0ajenz/QTQorZ1c2bfM+eMdcm2giHmskInd+i4QP9i5olm7Hl/t759btMqdK368QqRoaGH3Rhj97G8fjWSLLhFfb9Uu+S1P5AgC4qZytk26XfIstdfXgkXNl71oFteocMPhst1FU0eChmV9sSfFL3U93KgsArR+RIVdUv0wTzCSWCFtoLJI6WIgtwfn+BKtrixxV2NrRJIsYCMzZcGvP9vbgMW7Iw99G1G6+Iip3lp1TqZCVf1IWwmlbR+31h6IPj6KId/bGR3pA2pmzky5NNSb3IsY+HfhH5FH/slg8BJTcjSXGudqNDmnrAxLtS3udX+uBJd1fQ==
const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))
ENH37VpAo3qXDLhwRWlHRXoFldBcHdD+KTeqPcF9UHLhMQG0tGaThlqTAkr+lE1ntmSnHM6bk6MIRnjtqhukfM+/10sjolBH/d8FlXaMwxVVUr2kvIf6VHqmi4u0rmXKklONVyuZ4TYJwHLDbp5KSdeOWw0TwxteU+QnIgvKg/s7BgEJFHIzSpVxOOz0dOUSYzQ51hpjE5NeqWN893ruMQ==