【问题标题】:Index.html instead of client stuff on server sideIndex.html 而不是服务器端的客户端内容
【发布时间】:2015-11-06 00:45:00
【问题描述】:

如何为我的应用程序的客户端获取 index.html?

在server.js中定义索引页面是这样的

// load css styles
var css = '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> ';
css = css + '<style type="text/css">' +require('fs').readFileSync('./style.css').toString() + '</style>'

http.createServer(function (req, res) {
  // send basic http headers to client
  res.writeHead(200, {
      "Content-Type": "text/html",
      "Transfer-Encoding": "chunked"
  });
  // setup simple html page:
  res.write("<html>\n<head>\n<title>Newsfeed</title>\n" +css +"</head>\n<body>");

但我想获得一个 index.html,这样我就可以将纯 HTML 用于前端。

【问题讨论】:

  • 这太大了,无法很好地回答 SO,但是您需要编写单独的前端和后端。我更喜欢使用 REST API 将两者联系在一起,但将它们保存在单独的项目中(使用第三个共享库)。
  • 你已经用express标记了这个,所以这不能回答你的问题吗?

标签: javascript node.js express


【解决方案1】:

这可以解释长。 简短的回答是,您分离视图,并使用快速中间件进行路由。

您必须设置查看位置:

app.set('views', __dirname + '/yourViewDirectory');

将您的 index.html 放入 /views 文件夹

然后就可以使用res.render函数了:

res.render('index.html');

这是基础 express 服务器,在 localhost:3000/ 上呈现 index.html

var express = require('express');
var app = express();

app.set('views', __dirname + '/yourViewDirectory');
app.get('/', function (req, res) {
  res.render('index.html');
});

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});

【讨论】:

    猜你喜欢
    • 2011-05-28
    • 2019-12-14
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 2018-06-06
    • 2018-05-15
    • 2012-09-21
    相关资源
    最近更新 更多