20

我正在运行以下代码,但失败并出现以下错误。

用于列出 bucker 内所有对象的 AWS 代码

const http = require('http');
const host = '127.0.0.1';
const port = 5000;
const path = require('path')
const url = require('url')
const fs = require('fs')
var AWS = require('aws-sdk');



const laptopDate = JSON.parse(fs.readFileSync(`${__dirname}/data/data.json`, `utf-8`))

AWS.config.update({accessKeyId: '***', secretAccessKey: '***', region: 'ap-south-1'});
s3 = new AWS.S3({apiVersion: '2006-03-01'});

var params = { 
    Bucket: 'bucket-name'
}

const server = http.createServer(function(req, res){
    const path = url.parse(req.url, true).pathname
    const id = url.parse(req.url, true).query.id

    if (path === 'bucket' || path === '/')
      s3.listObjects(params, function (err, data) {
        if(err) throw err;
        res.writeHead(200, { 'Content-Type': 'text/html' });
        //const output = JSON.parse(data)
        console.log(data)
        res.end(data)
      });
});

server.listen(port, host, function(req, res) {
    console.log(`Server is listening on ${host} and ${port}`)

第一个输出是 console.log 会按预期显示所有内容。但是,将输出渲染到屏幕的 res.end 失败并出现以下错误。

The "chunk" argument must be of type string or an instance of Buffer. Received an instance of Object
    at ServerResponse.end (_http_outgoing.js:752:13)
    at Response.<anonymous> (D:\js\Extra\starter\index.js:30:13)
    at Request.<anonymous> (D:\js\Extra\starter\node_modules\aws-sdk\lib\request.js:364:18)
    at Request.callListeners (D:\js\Extra\starter\node_modules\aws-sdk\lib\sequential_executor.js:106:20)
    at Request.emit (D:\js\Extra\starter\node_modules\aws-sdk\lib\sequential_executor.js:78:10)
    at Request.emit (D:\js\Extra\starter\node_modules\aws-sdk\lib\request.js:683:14)
    at Request.transition (D:\js\Extra\starter\node_modules\aws-sdk\lib\request.js:22:10)
    at AcceptorStateMachine.runTo (D:\js\Extra\starter\node_modules\aws-sdk\lib\state_machine.js:14:12)
    at D:\js\Extra\starter\node_modules\aws-sdk\lib\state_machine.js:26:10
    at Request.<anonymous> (D:\js\Extra\starter\node_modules\aws-sdk\lib\request.js:38:9) {
  message: 'The "chunk" argument must be of type string or an instance of Buffer. Received an instance of Object',
  code: 'ERR_INVALID_ARG_TYPE',
  time: 2020-05-18T08:39:24.916Z
}
4

2 回答 2

12

删除这个res.writeHead(200, { 'Content-Type': 'text/html' });

而不是res.end(data)使用res.send(data)或更好呢res.send({ data })


编辑 我没有注意到你没有使用快递,试试这个:

res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify(data));
res.end();
于 2020-05-18T12:11:27.187 回答
2

如果这可能对某人有所帮助,确切地说,我使用的数据类型不是String,所以我对其进行了更改以解决此错误NumberString

于 2021-07-06T06:39:54.737 回答