阅读获取承诺的主体

qui*_*bit 38 javascript node.js fetch-api

我确信这有一个简单的答案,但对于我的生活,我无法弄清楚如何去做.

我有以下用于上传到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;
});
Run Code Online (Sandbox Code Playgroud)

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

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

const Client = { upload };
export default Client;
Run Code Online (Sandbox Code Playgroud)

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

Client.upload(this.file).then((data) => {
  console.log(data);
});
Run Code Online (Sandbox Code Playgroud)

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

有没有人对如何从客户端的响应正文中检索此信息有任何建议?

编辑:

data这个样子的,当我CONSOLE.LOG它:

数据console.log的屏幕截图

编辑2:

这是我使用Postman将文件发布到我的终端时得到的响应: 使用邮差的屏幕截图

Gab*_*gan 53

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

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

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

  • 如果我使用`response.text`或`response.blob`,我的`console.log(data)`会得到'undefined`.如果我使用response.json,我会收到语法错误:`Uncaught(在promise中)语法错误:在位置0的JSON中出现意外的标记U. 我认为'U'来自我的'Unique',所以我认为你走的是正确的轨道 (3认同)
  • 我只需要用`.text()`替换`.json()`,这就是我的解决方案.谢谢. (2认同)

qui*_*bit 7

@GabeRogan gave me the answer (and I had a typo, as expected)

这是我更新的前端代码,该代码返回响应正文:

Client.upload(this.file).then(response => response.text())
  .then((body) => {
    console.log(body);
  });
Run Code Online (Sandbox Code Playgroud)

body 是读取“唯一文件名:[FILE-NAME]”的字符串

编辑:

这是对Fetch API的很好解释,并读取了您从Promise对象获得的响应:https : //css-tricks.com/using-fetch/


spe*_*edy 7

您还可以使用异步/等待:

返回json内容时:

Client.upload(this.file).then(async r => console.log(await r.json()))
Run Code Online (Sandbox Code Playgroud)

或者只是以文本形式返回:

Client.upload(this.file).then(async r => console.log(await r.text()))
Run Code Online (Sandbox Code Playgroud)


小智 7

如果您收到数据“未定义”并且正在对响应执行某些操作,请确保返回响应。

我正在做这样的事情

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

返回响应对象:return response.text();

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