nodejs问题?

js代码:

var http = require('http')
var fs = require('fs')
var template =require('art-template')

var comments =[
    {
        name:'张三',
        message:'天气不错',
        datatime:'2020-6-24'
    },
    {
        name:'张三1',
        message:'天气不错',
        datatime:'2020-6-24'
    },
    {
        name:'张三2',
        message:'天气不错',
        datatime:'2020-6-24'
    },
    {
        name:'张三3',
        message:'天气不错',
        datatime:'2020-6-24'
    }
]
http.createServer(function (req,res) {
      var url = req.url
      if (url === '/') {
          fs.readFile('./public/html/homepage.html',function (err,data) {
              if (err) {
                  return res.end('404 not found')
              }
                  console.log('文件响应成功了!')
                  //↓渲染页面↓
                 var newhomepage = template.render = (data.toString(),{
                     comments:comments
                 })
                  res.end(newhomepage)
          })
      }
}).listen(8081, function () {
    console.log('服务器启动了!')
}  )

页面代码:

 <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            *{
                margin: 0;
                padding: 0;
            }
        </style>
    </head>
    <body style="height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;"
         >
        <h1>欢迎来到留言板主页!</h1>s
        <h2><a href="/public/html/write.html">创建留言</a></h2>
        <ul>
        
            {{each comments}}
            <li>名字:{{ $value.name }} 消息:{{ $value.message }} 日期:{{ $value.datatime }} </li>
             {{/each}}
             
        </ul>
    </body>
    </html>

控制台输出:

[Running] node "d:\vscode\codetest\nodejs~~~~~~~~\留言板\02.js"
服务器启动了!
文件响应成功了!
_http_outgoing.js:759
      throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
      ^

TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer. Received an instance of Object
    at ServerResponse.end (_http_outgoing.js:759:13)
    at d:\vscode\codetest\nodejs~~~~~~~~\留言板\02.js:38:23
    at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:63:3) {
  code: 'ERR_INVALID_ARG_TYPE'
}

好像是res.end出了问题,我把end后面括号里面的newhomepage换成一个随意的字符串就可以输出,帮帮孩子吧。_(:з」∠)_

阅读 4.4k
4 个回答

res.end()方法接收的参数类型只能是字符串或Buffer,传入的object报错。你的模版那里写错了

// render写成了赋值
var newhomepage = template.render(data.toString(),{
  comments:comments
})
res.end(newhomepage)

你的res.end 部分有问题。由于使用了逗号表达式,因此等价于:

res.end({
    comments:comments
})

这是不对的, res.end 函数签名没有这个重载。 res.end 里面应该是字符串或者 buffer

res.end,改成res.send试下

comments:JSON.stringify(comments)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题