读取 Fetch Promise 的主体

Read the body of a Fetch Promise

我有以下用于上传到 Google 云存储的快速端点。它工作得很好,google 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)

中写的回复

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

当我 console.log 它时 data 看起来像这样:

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

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

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

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

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

Ok awesome. To be quite honest I have absolutely no clue why you're getting undefined, except that it might be some sort of misspelling error?

这是我更新的前端代码,returns 响应正文文本:

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

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

下面是对 Fetch API 和读取从 promise 对象获得的响应的一个很好的解释:Css tricks: Using Fetch.

你也可以使用async/await:

返回json内容时:

Client.upload(this.file).then(async r => console.log(await r.json()))

或仅以文本形式返回:

Client.upload(this.file).then(async r => console.log(await r.text()))

如果您得到“未定义”的数据并且您正在对响应进行操作,请确保 return 响应。

我正在做这样的事情

fetch(URL)
    .then(response => {
        response.text();
        console.log(response.statusText);
    })
    .then(data => console.log(data)); // got "undefined"

Return响应对象:returnresponse.text();

fetch(URL)
    .then(response => {
        console.log(response.statusText);
        return response.text();
    })
    .then(data => console.log(data)); // got data