0

是否可以使用 node.js 动态创建页面(路由)?

假设我在 create-route.html 文件 ( localhost:4001/create-route ) 上的表单中有一个简单的文本输入,我要输入“my-page”,然后这会将我带到一个带有 url 的新视图localhost:4001/my-page 显示成功消息。

我不太确定这是否可行,因为我也不确定哪些节点模块将允许客户端访问 createServer 对象并对其进行操作。环顾 'Express' 经常被引用为 routing ,但在查看框架之前,我很想看看这是否可能仅在 Node 中实现。

任何帮助表示赞赏,谢谢。

网络服务器.js

var http = require('http')
, url = require('url')
, fs = require('fs')
, server;

// declare http object
server = http.createServer(function(req,res){

  // parse the pathname as a url, get the trimmed route from the request
  var path = url.parse(req.url).pathname;

  // handle the various routes
  switch(path){

    case '/':
      fs.readFile(__dirname + '/index.html', function (err, data) {
        if (err) throw err;
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data, 'utf8');
        res.end();
      });


    case '/create-route':
        fs.readFile(__dirname + '/create-route.html', function (err, data) {
        if (err) throw err;
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data, 'utf8');
        res.end();
    });

    // example of dynamically created 'route'
    // "value' indicates the name that was inputted into the for on create-route.html, which in this case should be "my-page"

    case '/value':
        if (err) {throw err;}
        var body = "<html>" + 
            "<head>" +
            "<meta http-equiv='Content-Type' content='text/html'" +
            "charset=UTF-8 />" +
            "</head>" +
            "<body>" +
            "<p>youve just created a page called " + value + "</p>" +
            "</body>" +
            "</html>";
        res.writeHead(200, {"Content-Type": "text/html"});
        res.write(body);
        res.end();
    });

    break;

    default: send404(res);
  }
});

创建-route.html

<html>
<head>
    <title>Create a route</title>
</head>
<body>
    <form action="/go-to-the-created-route">
        <label>Enter a route name:</label>
        <input type="text" name="create-route" id="create-route">
        <button type="submit">Submit</button>
    </form>
</body>
</html>

根据反馈更新路线

这是根据@penartur 反馈更新的“创建路线”路线。

// Define the go-to-created-route
routes["go-to-created-route"] = function (req, res) {

// get the request url and split it to get the inputted value
var reqPath = req.url;
var splitPath = reqPath.split("=");
var routeName = splitPath[(splitPath.length - 1)]; // outputs the value entered into text input
//console.log(routeName); 

// create the new route by passing in the value of routeName, and display a page
routes[routeName] = function (req, res) {

// Not getting in here :(
    console.log("hello?");

    var body = "<html>" + 
        "<head>" +
        "<meta http-equiv='Content-Type' content='text/html'" +
        "charset=UTF-8 />" +
        "</head>" +
        "<body>" +
        "<p>youve just created a page called " + routeName + "</p>" +
        "</body>" +
        "</html>";
     res.writeHead(200, {"Content-Type": "text/html"});
     res.write(body);
     res.end();
};
};
4

2 回答 2

1

这是一个简单的编程问题,与具体的 Node.js 没有太大关系。解决方案草案:

var http = require('http')
, url = require('url')
, fs = require('fs')
, server;

var routes = {};

routes["create-route"] = function (req, res) {
    fs.readFile(__dirname + '/create-route.html', function (err, data) {
        if (err) throw err;
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data, 'utf8');
        res.end();
    });
};

routes["go-to-the-created-route"] = function (req, res) {
    var routeName = req.body["create-route"];
    routes[routeName] = function (req, res) {
        var body = "<html>" + 
            "<head>" +
            "<meta http-equiv='Content-Type' content='text/html'" +
            "charset=UTF-8 />" +
            "</head>" +
            "<body>" +
            "<p>youve just created a page called " + routeName + "</p>" +
            "</body>" +
            "</html>";
        res.writeHead(200, {"Content-Type": "text/html"});
        res.write(body);
        res.end();
    };
};

// declare http object
server = http.createServer(function(req,res){

    // parse the pathname as a url, get the trimmed route from the request
    var path = url.parse(req.url).pathname;

    var firstPart = path.split('/')[1];
    if (routes.hasOwnProperty(firstPart)) {
        routes[firstPart](req, res);
    } else {
        send404(res);
    }
});
于 2012-07-30T05:12:54.430 回答
0
var http = require('http');

http.createServer(function(req,res){

var path = req.url.replace(/\/?(?:\?.*)?$/, '').toLowerCase();

switch(path) {
    case '':
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('Homepage');
        break;
    case '/getapi':
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end('<div>Hello world!</div>');
    break;
    default:
        res.writeHead(404, { 'Content-Type': 'text/html' });
        res.end('Not Found');
    break;
}

}).listen(4000);
于 2021-03-31T06:00:52.900 回答