res.sendFile不是Node.js的一个函数。

10

我无法使用node.js发送HTML文件。

首先,这是我收到的错误信息:

Application has thrown an uncaught exception and is terminated:
TypeError: res.sendFile is not a function
    at Server.<anonymous> (C:\Program Files\iisnode\www\test\app.js:4:6)
    at emitTwo (events.js:88:13)
    at Server.emit (events.js:173:7)
    at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:529:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:89:23)

我的 app.js 代码是

var http = require('http');

http.createServer(function (req, res) {
    res.sendFile('test.html', { root: __dirname });
}).listen(process.env.PORT);  

如果我错过了什么简单的东西,对不起,因为这是我制作的第一个node.js程序。


2
我认为sendFileExpressJS响应方法。您需要安装并使用Express才能使用它。 - Andy
10个回答

29

这个具体问题已经得到了答复,但值得一提的是,如果您正在使用“express”版本 3.x,则修复可能就像将 res.sendFile('path-to-file'); 切换为 res.sendfile('path-to-file'); 这么简单。

在我的情况下,这就是问题所在。因此,您可以升级 express 版本 (或) 更改方法名称为小写来解决此问题。


这个救了我的命 :D - chrizonline
又救了一个生命! - php_nub_qq
再来一次。谢谢 :) - Snappy
哎呀,让我登录才能给你的答案点赞。;-) 谢谢! - Rodger

15

sendFile只能在Express模块中使用。

尝试使用此代码。

 var express = require('express');
 var app = express();
 app.get('/', function(req, res) {
     res.sendFile('path-to-file');
 });
 app.listen(PORT);

3
请注意,直到安装Express之前,这将无法正常工作。 - Andy
啊,我的回答应该只是你的评论。干得好,先生或女士。 - Fissure King
问题在于Express似乎没有安装,尽管我认为我已经安装了它。 - jLynx
1
@DarkN3ss 首先安装 Express。npm install express --save - Toanalien

8
借助Toanalien(正确的)答案,您可以通过以下方式完成相同的操作:
var http = require('http');
var fs = require('fs');
var path = require('path');

http.createServer(function (req, res) {
  // maybe test for existence here using fs.stat

  res.writeHead(200, {"Content-Type": "text/html"});

  fs.createReadStream(path.resolve(__dirname, 'test.html')) 
    .pipe(res);

}).listen(process.env.PORT || '3000'); // provide a default  

请查看http.ServerResponsefs.createReadStream

1
谢谢你。这也解决了我的问题。 - Kat

5
我也曾遇到过同样的问题,这个方法对我有用。希望它对你也有效。
 function(req,res){};
  • 第一个参数应该是"req" *

2

上面的答案是正确的,我只是添加了一个没有express.js但有route dispatcher的工作示例。

var http = require('http');                                                                         
var Router = require('routes');                                                                                                                                                   
var router = Router();                                                                                 
var fs = require('fs')                                                                         

router.addRoute("GET /test", (req, res, params) => {  
    let file = __dirname + '/views/test.html'                                                     
    res.writeHead(200, {"Content-Type": "text/html"});                                                 
    fs.createReadStream(file).pipe(res);                        
});                                                                                                    

var server = http.createServer((req, res) => {                                                   
 var match = router.match(req.method + ' ' + req.url);                                                 
 if (match) match.fn(req, res, match.params);                                                          
 else {                                                                                                
  res.statusCode = 404;                                                                                
  res.end('not found\n');                                                                              
 }                                                                                                     
}).listen(process.env.PORT || 3000);

调用端点/test将返回views/test.html

package.json是,

{                                                                                                                                                                                 
  "name": "node-app",                                                                                  
  "version": "1.0.0",                                                                                  
  "description": "node api",                                                                           
  "main": "server.js",                                                                                 
  "scripts": {                                                                                         
    "test": "echo \"Error: no test specified\" && exit 1"                                              
  },                                                                                                   
  "author": "prayagupd",                                                                               
  "license": "ISC",                                                                                    
  "dependencies": {
    "request": "^2.75.0",                                                                              
    "request-promise": "^4.1.1",                                                                       
    "routes": "^2.1.0"                                                                                 
  }                                                                                                    
}

1

试一试吧,伙计们

const index = path.resolve(root + '/index.html');
const http = require('http');

const server = http.createServer((req, res) => {
   res.setHeader('Content-Type', 'text/html');
   fs.createReadStream(index).pipe(res);
});

如果您没有使用express,那么这将是正确且最佳的答案。 - paulofer85

1
app.get("/", function(req,res){
    res.sendFile(__dirname + "/html filename with .html extension");
});

请注意,在函数的第一个参数必须是req,然后是res,请确保您已经这样做了,因为有时候我们因为一些小错误而得到错误。

这是我的个人经验,我尝试了所有的解决方案,但当我检查我的代码时,我发现我把res写成了第一个参数,而将req写成了第二个参数。


这也是我的情况。谢谢你提醒我! - omsharp

0

在终端中使用以下命令(适用于Ubuntu系统)安装Express:

npm install express

0
在我的情况下,这是因为该函数需要两个参数,但我像这样分配了3个:
app.use(function notFoundHandler(err, req, res) {
    res.sendFile('404.html');
})

然后我移除了 'err' 参数,它就完美地工作了。像这样:

app.use(function notFoundHandler(req, res) {
    res.sendFile('404.html');
})

-1

嗯,我已经进行了一些测试,主要问题是回调函数必须有两个参数(req,res)=>{},如果没有这个参数会抛出错误,当然需要安装express作为依赖。 您给参数命名并不是非常重要的,但如果必须只使用一个参数,则将其解释为 req。


这个答案非常误导和令人困惑。没有必要有两个参数,这样做也不会导致任何错误。在JavaScript中,参数是按位置传递的(而不是按名称)。这意味着请求将始终是第一个参数,无论名称如何,第二个参数将是响应,无论名称如何。如果您只放置一个参数,则该参数将仅为请求,并且您将无法获得响应对象。我认为这就是您所暗示的,但是答案非常不清楚。请编辑您的答案,以便其他读者可以更好地理解您的意思。 - Jesse

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接