【问题标题】:Using ExpressJS: How to use app.use to serve static files vs. app.get()?使用 ExpressJS:如何使用 app.use 提供静态文件与 app.get()?
【发布时间】:2017-12-01 21:58:58
【问题描述】:

我正在使用 express 来提供文件并且一切正常,但我无法让我的 console.log 语句显示在 app.get() 路由语句中。我目前使用app.use(express.static("public")); 从公用文件夹提供服务。

这里是完整的代码:

//Server static files from the public folder.
app.use(express.static("public"));

app.listen(PORT, function(){
console.log("Sever is running and listening on port: " +PORT);
});

//Establish routes
app.get('/', function (req, res) {
//res.sendFile('/student-profile');
res.send("This is the response.");
});

1) 我怎样才能得到这项工作?

2) 另外,从公用文件夹提供静态文件时,index.html 是否是第一个查找的文件?

【问题讨论】:

  • 你是进口快递吗?例如:const express = require('express'); const app = express();?
  • 是的,它们已被导出。
  • 我发现在使用express.static('public'); 时不需要app.get('/') 但是,对于任何POST 请求,您都需要一个post route 方法。

标签: express


【解决方案1】:
/* directories
public
views
app.js
*/

// create server
const express = require('express');
const app = express();
// import path
const path = require('path');
// use static directory
app.use(express.static(path.join(__dirname, 'public')));

app.get("/", (req, res, next) => {
   res.send("This is the response.")
   // if you want to render a template then
   // in the {} you can send data with

   //res.render("FileName", {})
})

app.listen(PORT, () => {
   console.log("Sever is running and listening on port: " +PORT);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 2014-11-20
    • 2018-09-21
    • 2016-11-13
    • 2014-01-12
    • 2013-06-10
    • 1970-01-01
    相关资源
    最近更新 更多