【问题标题】:Having trouble with the node express API节点 Express API 遇到问题
【发布时间】:2019-12-01 10:42:07
【问题描述】:

我尝试过this 教程,了解如何设置本地主机,有些代码有效,有些则无效。但目前我收到了奇怪的体验:

res.sendfile 的代码下方,重要的是要提到终端将该命令设置为已弃用。

使用res.sendFile 会出现following 错误。

我尝试过将.sendFile 与绝对路径一起使用,但没有成功:

res.sendFile('localhost:3000/client/index.html');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = 3000;

app.get('/', function(req, res){
    res.sendfile('client/index.html');
});

我只是想在 server.js 和 index.html 之间建立一个简单的连接。预期的输出是显示index.html 而不是错误。

【问题讨论】:

  • res.sendFile(__dirname + '/client/index.html');
  • 哦,等等,认真的吗?我到处都看到了这个答案,但我主要认为它必须由绝对链接代替。我以为它是未定义的。哦上帝...非常感谢您的回答!我想我们现在可以锁定它了?
  • 你想让我把它作为答案发布吗?
  • @StephenS 那太理想了。

标签: express localhost sendfile


【解决方案1】:

您可以使用__dirname 变量来存储当前执行脚本的绝对路径。您可以在sendFile 函数中附加此路径。

res.sendFile(__dirname + '/client/index.html');

您也可以使用 Node.js path 模块来连接路径

const path = require('path');
...
...
res.sendFile(path.join(__dirname,'/client/index.html'));

path.join 确保在 UNIX / Windows 系统中正确的斜线。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-31
    • 2022-01-01
    • 2019-09-06
    • 1970-01-01
    • 2020-02-18
    • 2022-11-04
    • 2016-12-18
    • 1970-01-01
    相关资源
    最近更新 更多