Read the body of a Fetch Promise

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:

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)

How I can retrieve this info from the response body on the client-side?

The data looks like this when I console.log it:

Screenshot of the data console.log

This is the response I get when I POST a file to my endpoint using Postman:

Screen shot of response using Postman

138911 次浏览

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

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

如果这会给您带来意想不到的结果,您可能需要使用 邮差检查响应。

正如 此评论中的 GabeRogan指出的那样,我的代码中有一处输入错误:

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

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

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

body是读取 Unique File Name: [FILE-NAME]的字符串

下面是对 FetchAPI 的一个很好的解释,以及读取您从承诺对象 CSS 技巧: 使用 Fetch获得的响应。

还可以使用异步/等待:

返回 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()))

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

我正在做类似的事情

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

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

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