简体   繁体   English

在Express中设置主页

[英]Set Home Page in Express

I have some server side code in node js, which creates a express js object and runs the server. 我在节点js中有一些服务器端代码,它创建了一个快速js对象并运行服务器。 The app loads the index.html page which is inside the public folder. 该应用会加载位于公共文件夹内的index.html页面。 I have never written the code to serve the home page (mention below), still it works. 我从未写过用于服务主页的代码(在下面提到),但它仍然有效。

app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'public/index.html'));
});

I have not written this code so how does the index.html gets rendered. 我尚未编写此代码,所以如何呈现index.html。 My understanding says express JS looks for the first instance of index.html page in all the static folders declared in the code and renders it, in my case the static folder is "publimc" and it has index.html at the root level. 我的理解是,Express JS在代码中声明的所有静态文件夹中查找index.html页面的第一个实例并将其呈现,在我的情况下,该静态文件夹为“ publimc”,并且在根目录下具有index.html。

server code follows below, which I have written. 服务器代码如下,这是我写的。

var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('contactlist', ['contactlist']);
var bodyParser = require('body-parser');


app.use(express.static(__dirname + '/publimc'));
app.use(bodyParser.json());

app.get('/contactlist', function (req, res) {
  console.log('I received a GET request');
  db.contactlist.find(function (err, docs) {
  console.log(docs);  
  res.json(docs);
  }); 
});

app.listen(8000);
console.log("Server running on port 8000");

The home page is rendered as part of the express.static middleware default options . 主页呈现为express.static中间件默认选项的一部分

To disable this logic, set express.static(..., { index: false }) . 要禁用此逻辑,请设置express.static(..., { index: false })

If you want to change the file served as a home page, set express.static(..., { index: 'yourfile.html' }) . 如果要更改用作主页的文件,请设置express.static(..., { index: 'yourfile.html' })

What this option does, in fact, is attempt to serve an index page with given file name for each directory in your public folder, so if you have public/foo/index.html then it will get served when requesting /foo/ path. 实际上,此选项的作用是尝试为公用文件夹中每个目录的给定文件名提供一个索引页,因此,如果您具有public/foo/index.html则在请求/foo/路径时它将得到服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM