使用查询字符串表示 res.sendFile()

Kri*_*kar 10 html static node.js express

我已经使用 res.sendFile() 成功实现了提供静态文件,但是如果我添加一些查询字符串,它就不起作用。

例如,下面的代码工作得很好。

res.sendFile(path.join(__dirname, '../public', '/index.html'));
Run Code Online (Sandbox Code Playgroud)

但如果我这样做,它就会失败

res.sendFile(path.join(__dirname, '../public', '/index.html?id=' + req.params.id));

res.sendFile(path.join(__dirname, '../public', '/index.html?id=123'));
Run Code Online (Sandbox Code Playgroud)

然后我得到以下错误

ENOENT, stat '/Users/krishnandu/Documents/Project/public/index.html?id=123'

404

Error: ENOENT, stat '/Users/krishnandu/Documents/Project/public/index.html?id=123'
    at Error (native)
Run Code Online (Sandbox Code Playgroud)

小智 6

您不能使用res.sendFile(). 您必须将文件路径指定为第一个参数res.sendFile()

语法是:

res.sendFile(path [, options] [, fn])
Run Code Online (Sandbox Code Playgroud)

所以你能做的是,

  1. 使用带有路由的查询字符串,比如route1(请参阅下面的代码)

  2. route1的 GET 方法中,使用res.sendFile()

    app.get('/route1',function(req,res){
      res.sendFile(path.join(__dirname, '../public', '/index.html'));
    });
    
    res.redirect('/route1?id=123');
    
    Run Code Online (Sandbox Code Playgroud)

又见快递API文档res.sendFileres.redirect

  • 如何访问`index.html`中的`id`? (14认同)

Can*_*ide 5

这个答案是通过在评论中涵盖@Sky 提出的问题来进一步补充@Marie Sajan 的答案。

idindex.html使用@Marie Sajan 的答案后访问,您可以使用普通的客户端 JavaScript。<script>您可以在 html 文件的标签中执行类似的操作:

var query = location.href.split("?")[1];

这将为您提供一个字符串,例如“id=123&name=ted”。从这里您可以使用 javascript 来获取 的值id。完整的代码可能如下所示:

var query = location.href.split("?")[1]; //A string of all parameters in the URL
var params = query.split("&"); //Turns the string into an array of parameters
var id; //To store the value of id

params.forEach((param, index) => {
    //This checks each key-value pair, in the format key=value, for the specific id key we want
    var key = param.split("=")[0]; //In id=123, this would be "id"
    var value = param.split("=")[1]; //In id=123, this would be "123" (as a String)
    if (key == "id") id = value;
});
Run Code Online (Sandbox Code Playgroud)

现在 JavaScript 变量id将包含值“123”。

如果除了键之外,您还需要查找更多查询参数的值id,则只需if在 中添加更多语句forEach来检查这些特定键。

在诸如“ http://google.com/?q=stack+overflow&id=123 ”之类的链接中,id当直接在 HTML 文件中实现为客户端 JavaScript 时,此代码将能够获取值“123”在<script>标签中,或者在 HTML 文件使用的单独的客户端 js 文件中。请注意,@Marie Sajan 的答案完全是服务器端代码,而此代码将在客户端使用。

此答案并未解决原始问题,它只是根据本页面查看者的需求在已接受的问题答案中添加了更多有用的内容。