我有以下用于上传到谷歌云存储的快速端点.它工作得很好,来自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)中所写的回复

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

当我安慰时,data是这样的.记录它:

Screenshot of the data console.log

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

Screen shot of response using Postman

推荐答案

注意,你要面对的是Response object.为了查看数据,您需要使用Response.json()Response.text()(或通过其他方法)查看响应流.否则,您的响应正文将始终显示为锁定的可读流.例如:

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

如果这给了你意想不到的结果,你可能想用Postman判断你的回答.

Node.js相关问答推荐

node 模块错误:类型参数OT具有循环约束''

容器端口是容器内 node 应用程序的端口吗?

在Node JS中获取控制台选项卡标题

如何在ejs模板中使用循环显示多个结果?

JsonwebToken过期后如何注销和清除cookie?

Node.js中Redis的并发问题

如何在Mongoose for MongoDB中编写此查询

使用 axios 和 Cheerio (Node js) 抓取 google 搜索

Next.js 路由不起作用 - 页面未正确加载

在 azure blob 容器之间复制文件

未捕获的错误: 只能用作 元素的子元素,永远不会直接呈现.请将您的 包裹在

Express.js cookie setter 的 Domain 属性:如何与 *多个 * 域共享 cookie?

[NodeJs 从 ADAL 升级到 MSAL]:无法在字符串上创建属性authenticationScheme

在 Express.js 中迭代子文档数组

Mongodb v4.0 Transaction, MongoError: Transaction numbers are allowed on a replica set member or mongos

从目录 node Js 中检索文件

MongoDB Node findone如何处理没有结果?

使用 MongoDB 更新嵌套数组

如何让should.be.false语法通过 jslint?

如何判断 Node.js 中是否设置了环境变量?