【问题标题】:How to create subpages with node.js using Amazon EC2 and heroku如何使用 Amazon EC2 和 heroku 使用 node.js 创建子页面
【发布时间】:2014-01-07 03:19:46
【问题描述】:

我是一名初级程序员,对 Node.js 还很陌生。 我设法使用 AWS EC2 和 Heroku 设置了一个静态页面,但我需要帮助来制作其他子页面。 IE。 mysite/blog 或 mysite/archive。

我从一个简单的 web.js 文件开始,该文件是从一个示例节点应用程序中获得的:

var express = require('express');
var app = express();
app.use(express.logger());

app.get('/', function(request, response) {
  response.send('Hello World!');
});

var port = process.env.PORT || 5000;
app.listen(port, function() {
  console.log("Listening on " + port);

说的都是 Hello World,所以我创建了 index.html 并将 web.js 更改为这个。

var express = require('express');
var fs = require('fs');
var htmlfile = "index.html";
var app = express(express.logger());

app.get('/', function(request, response) {
var html = fs.readFileSync(htmlfile).toString();
response.send(html);
});

var port = process.env.PORT || 8080;
app.listen(port, function() {
  console.log("Listening on " + port);

现在改为使用 index.html,但如何让 /blog 或 /archive 工作?

【问题讨论】:

    标签: javascript node.js heroku amazon-ec2


    【解决方案1】:

    您可以在代码中添加其他路由来处理特定的 URL 格式。确保更具体的 URL 列在一般路由(/ 或 *)之前

    // Handle request for blog
    app.get('/blog', function(req, res){
      res.send('A list of blog posts should go here');
    });
    
    // Handle request for archive
    app.get('/archive', function(req, res){
      res.send('Archive content should go here');
    });
    
    // Route for everything else.
    app.get('*', function(req, res){
      res.send('Hello World');
    });
    

    我在这里有更详细的解释:http://hectorcorrea.com/#/blog/introduction-to-node-js/51

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-27
      • 2015-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-07
      • 2015-08-16
      相关资源
      最近更新 更多