【问题标题】:Serve static files for an URL with dynamic params in node js without any library or framework在没有任何库或框架的节点 js 中为具有动态参数的 URL 提供静态文件
【发布时间】:2019-12-11 23:52:32
【问题描述】:

我这里有个小问题。 我想用一个简单的节点服务器为“/user/:id”URL 提供一个静态文件。 这怎么可能? 这是我在客户端的请求:

document.location.href = `http://localhost:8080/user/${x}`;

这是我的请求处理程序:

var routeHandler;
if (req.method === 'GET') {
        switch (req.url) {
            case '/user/:id':
                routeHandler = userProvider;
                break;
        }
}

function userProvider(req, res) {
        req.url = 'index.html';
        staticFileHandler(req, res);
}

function staticFileHandler(req, res) {
        fs.readFile('client/' + req.url, function (err, data) {
            if (err) {
                res.writeHead(500);
                res.write(err.name);
                res.end();
            }
            res.writeHead(200);
            res.write(data);
            res.end();
        });
    }

有没有办法只使用 nodejs 而不使用 express 或任何其他库来处理这个请求?

【问题讨论】:

    标签: javascript node.js server xmlhttprequest


    【解决方案1】:

    由于req.url 不会与case '/user/:id': 完全匹配,因此不要使用switch

    改用正则表达式的if 测试。

    if ( req.url.match(/^\/user\/\d+/);
    

    【讨论】:

    • 在 userProvider 函数中,我更改了 req.url,但它在每个 req.url 的开头添加了“/user/”!!!我该如何解决这个问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 2013-10-11
    相关资源
    最近更新 更多