阅读获取承诺的正文

2022-08-30 05:30:29

我有以下用于上传到Google Cloud存储的快速终端节点。它工作得很好,谷歌api的响应给了我一个唯一的文件名,我想把它传回我的前端:

app.post('/upload', (req, res) => {
  var form = new formidable.IncomingForm(),
  files = [],
  fields = [];

  form
    .on('field', function(field, value) {
      fields.push([field, value]);
    })
    .on('file', function(field, file) {
      files.push([field, file]);
    })
    .on('end', function() {
      console.log('-> upload done');
    });
  form.parse(req, function(err, fields, files){
    var filePath = files.file.path;
    bucket.upload(filePath, function(err, file, apiResponse){
      if (!err){
        res.writeHead(200, {'content-type': 'text/plain'});
        res.end("Unique File Name:" + file.name);
      }else{
        res.writeHead(500);
        res.end();
      }
    });
  });

 return;
});

我通过调用一个将文件传递给它的短函数来到达这个端点:

function upload(file) {
  var data = new FormData();
  data.append('file', file);
  return fetch(`upload`,{
    method: 'POST',
    body: data
  });
}

const Client = { upload };
export default Client;

这个函数是从我的前端调用的,如下所示:

Client.upload(this.file).then((data) => {
  console.log(data);
});

此最终将响应记录到控制台。但是,我没有在任何地方看到我写的响应(console.log(data)"Unique File Name:" + file.name)

如何从客户端的响应正文中检索此信息?

当我控制台时看起来像这样.log它:data

Screenshot of the data console.log

这是我使用Postman将文件发布到我的端点时得到的响应:

Screen shot of response using Postman


答案 1

请注意,您正在处理响应对象。您基本上需要使用或(或通过其他方法)读取响应流才能查看数据。否则,您的响应正文将始终显示为锁定的可读流。例如:Response.json()Response.text()

fetch('https://api.ipify.org?format=json')
.then(response=>response.json())
.then(data=>{ console.log(data); })

如果这给您带来了意想不到的结果,您可能需要使用Postman检查您的回复。


答案 2

我的代码中有一个拼写错误,正如GabeRogan在此评论中指出的那样:

好吧,真棒。说实话,我完全不知道为什么你没有得到定义,除了它可能是某种拼写错误?

以下是我为前端更新的代码,它返回响应正文文本:

Client.upload(this.file).then(response => response.text())
  .then((body) => {
    console.log(body);
  });

body是一个字符串,内容为Unique File Name: [FILE-NAME]

以下是对 Fetch API 的一个很好的解释,并阅读了你从 promise 对象获得的响应:Css 技巧:使用 Fetch