[英]TypeError: Cannot read property 'length' of undefined in Node.js
I'm trying to create a server but it is throwing me an error in console 我正在尝试创建服务器,但它在控制台中抛出了一个错误
$ node server1185
Server listening at 1185
C:\Users\Bharat\Desktop\Nodejs\server1185.js:9
res.writeHead(200,{'Content-Type':'text/html', 'Content-Length': data.length
^
TypeError: Cannot read property 'length' of undefined
at ReadFileContext.callback (C:\Users\Bharat\Desktop\Nodejs\server1185.js:9:
71)
at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:420:13)
My Node.js code is following 我的Node.js代码如下
var http = require('http'); var fs = require('fs'); var server = http.createServer(function(req, res){ displayForm(res); }); function displayForm(res){ fs.readFile('form.html', function(err,data){ res.writeHead(200,{'Content-Type':'text/html', 'Content-Length': data.length }); res.write(data); res.end(); }); } server.listen(1185); console.log('Server listening at 1185');
You have to handle the err
object properly Log both err
and data
object. 您必须正确处理
err
对象记录err
和data
对象。 You will understand the problem 您将了解问题
if(err)
{
console.log(err)
}
else
{
res.writeHead(200,{'Content-Type':'text/html', 'Content-Length': data.length
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.