简体   繁体   English

TypeError:无法读取Node.js中未定义的属性“ length”

[英]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'); 
It is throwing an error in data.length, an explanation will be appreciated. 它在data.length中引发错误,将不胜感激。

You have to handle the err object properly Log both err and data object. 您必须正确处理err对象记录errdata对象。 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.

相关问题 未捕获的类型错误:无法读取 node.js 上未定义的属性“长度” - Uncaught TypeError: Cannot read property 'length' of undefined on node.js TypeError无法读取节点js中未定义的属性'length' - TypeError cannot read property 'length' of undefined in node js 无法读取未定义的Node.js和Jade的属性“长度” - Cannot read property 'length' of undefined Node.js & Jade Pug/Node.Js:无法读取未定义的属性“长度” - Pug/Node.Js: Cannot read property 'length' of undefined Node.js 抛出 TypeError:无法读取未定义的属性“testModule” - Node.js throwing TypeError: Cannot read property 'testModule' of undefined TypeError:无法读取未定义的属性“ get”(Node.js) - TypeError: Cannot read property 'get' of undefined (Node.js) TypeError:无法读取node.js中未定义的属性“名称” - TypeError: Cannot read property 'name' of undefined in node.js Node.js UnhandledPromiseRejection:TypeError:无法读取未定义的属性“ sign” - Node.js UnhandledPromiseRejection: TypeError: Cannot read property 'sign' of undefined Node.js -> TypeError:无法读取上下文中未定义的属性“then” - Node.js -> TypeError: Cannot read property 'then' of undefined at Context TypeError:无法读取未定义(Promise)(node.js)的属性“ then” - TypeError: Cannot read property 'then' of undefined (Promise) (node.js)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM