Javascript 读取 Fetch Promise 的主体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43903767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read the body of a Fetch Promise
提问by quicklikerabbit
I'm sure this has a simple answer, but for the life of me I can't figure out how to do it.
我相信这有一个简单的答案,但对于我的生活,我不知道该怎么做。
I have the following express endpoint for uploading to Google Cloud storage. It works great and the response from the google api gives me a unique file name that I want to pass back to my front end:
我有以下用于上传到 Google Cloud 存储的快速端点。它工作得很好,来自 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;
});
I reach this endpoint by calling a short function which passes the file to it:
我通过调用一个将文件传递给它的短函数来到达这个端点:
function upload(file) {
var data = new FormData();
data.append('file', file);
return fetch(`upload`,{
method: 'POST',
body: data
});
}
const Client = { upload };
export default Client;
This function is called from my front end like this:
这个函数是从我的前端调用的,如下所示:
Client.upload(this.file).then((data) => {
console.log(data);
});
This final console.log(data)logs the response to the console. However, I don't see anywhere the response that I wrote in ("Unique File Name:" + file.name)
最后console.log(data)将响应记录到控制台。但是,我在任何地方都看不到我在 ( "Unique File Name:" + file.name) 中写的回复
Does anyone have any suggestions for how I can retrieve this info from the response body on the client side?
有没有人对我如何从客户端的响应正文中检索此信息有任何建议?
EDIT:
编辑:
The datalooks like this when I console.log it:
该data是这样的,当我CONSOLE.LOG它:
EDIT 2:
编辑2:
This is the response I get when I POST a file to my endpoint using Postman:

回答by Gabe Rogan
Notice you're dealing with a Response object. You need to basically readthe response stream with Response.json()or Response.text()(or via other methods) in order to see your data. Otherwise your response body will always appear as a locked readable stream. For example:
请注意,您正在处理Response 对象。您基本上需要使用或(或通过其他方法)读取响应流才能查看您的数据。否则,您的响应正文将始终显示为锁定的可读流。例如:Response.json()Response.text()
fetch('https://api.ipify.org?format=json')
.then(response=>response.json())
.then??(data=>{ console.log(data); })
If this gives you unexpected results, you may want to inspect your response with Postman.
如果这会给您带来意想不到的结果,您可能需要使用Postman检查您的回复。
回答by quicklikerabbit
@GabeRogan gave me the answer (and I had a typo, as expected)
@GabeRogan 给了我答案(正如预期的那样,我有一个错字)
Here's my updated code for the front end which returns the response body text:
这是我更新的前端代码,它返回响应正文:
Client.upload(this.file).then(response => response.text())
.then((body) => {
console.log(body);
});
bodyis a string that reads "Unique File Name: [FILE-NAME]"
body是一个字符串,内容为“唯一文件名:[FILE-NAME]”
EDIT:
编辑:
Here's a good explanation of the Fetch API and reading the response you get from the promise object: https://css-tricks.com/using-fetch/
这是 Fetch API 的一个很好的解释,并阅读了你从 promise 对象得到的响应:https: //css-tricks.com/using-fetch/
回答by spedy
You can also use async/await:
您还可以使用异步/等待:
When returning json content:
返回json内容时:
Client.upload(this.file).then(async r => console.log(await r.json()))
or just returning in textual form:
或者只是以文本形式返回:
Client.upload(this.file).then(async r => console.log(await r.text()))

