将数据从 Node.js 发送回客户端
Posted
技术标签:
【中文标题】将数据从 Node.js 发送回客户端【英文标题】:Send data from Node.js back to Client 【发布时间】:2022-01-09 04:19:22 【问题描述】:我有一个 ios React Native 应用程序,它使用 Node.js 程序从 Google Cloud 存储桶下载照片。我可以从特定文件夹中获取照片,但无法将它们发送回客户。下面是客户端 Node.js 程序:
index.js
const express = require('express')
const bodyParser = require('body-parser')
const multer = require('multer')
const uploadImage = require('./helpers/helpers')
const downloadImage = require('./helpers/downloadhelpers');
const app = express()
const multerMid = multer(
storage: multer.memoryStorage(),
limits:
// no larger than 5mb.
fileSize: 25 * 1024 * 1024,
//fileSize: maxSize
,
)
app.disable('x-powered-by')
app.use(multerMid.single('file'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded(
extended: false
))
app.post('/uploads', async (req, res, next) =>
try
const myFile = req.file
const destination = req.body.folder_name;
const imageUrl = await uploadImage(myFile, destination)
res
.status(200)
.json(
message: "Upload was successful",
data: imageUrl
)
catch (error)
next(error)
)
app.get('/file_download', async (req, res, next) =>
const folder_name = req.body.folder_name;
try
const ImageDownload = await downloadImage(folder_name)
console.log(ImageDownload);
res
.status(200)
.json(
message: "Download Successful",
data: ImageDownload
)
catch (error)
next(error)
)
app.use((err, req, res, next) =>
res.status(500).json(
error: err,
message: 'Internal server error!',
)
next()
)
app.listen(9001, () =>
console.log('app now listening for requests!!!')
)
以下是正常工作的上传节点:
helpers.js
const util = require('util');
const gc = require('./../config')
const bucket = gc.bucket('jtg_app_bucket') // should be your bucket name
module.exports = uploadImage = (File, destination) => new Promise((resolve, reject) =>
const
originalname,
buffer
= File
const folder_name = destination;
console.log(folder_name);
const blob = bucket.file(destination + '/' + originalname.replace(/ /g, "_"))
const blobStream = blob.createWriteStream(
resumable: false
)
blobStream.on('finish', () =>
const publicUrl = util.format(
`https://storage.googleapis.com/$bucket.name/$folder_name.name/$blob.name`
)
resolve(publicUrl)
)
.on('error', () =>
reject(`Unable to upload image, something went wrong`)
)
.end(buffer)
)
以下是从 GCP 存储桶获取数据后发送数据的下载节点:
下载helpers.js
module.exports = downloadImage = (FolderToDisplay) => new Promise((resolve, reject) =>
const folder_name = FolderToDisplay;
const
Storage
= require('@google-cloud/storage');
var projectId = '*****************' // Your Google Cloud Platform project ID
var keyFilename = './../UploadPhotosNode/config/keys.json'
const storage = new Storage(
keyFilename,
projectId
);
var bucket = storage.bucket("gs://jtg_app_bucket");
const bucketName = 'jtg_app_bucket';
// The directory prefix to search for
const prefix = folder_name + '/';
// The delimiter to use
const delimiter = '/';
const options =
prefix: prefix,
;
bucket.getFiles(options).then(results =>
const files = results[0];
var resData =
success: true,
images:
results: []
;
files.forEach(file =>
resData.images.results.push(
uri: 'https://storage.googleapis.com/' + bucketName + '/' +
file.name
);
)
var stringified = JSON.stringify(resData);
var only_images = JSON.parse(stringified);
const data = only_images.images.results;
console.log(data);
resolve(data)
)
.on('error', () =>
reject(`Unable to download images, something went wrong`)
)
.end(buffer)
)
以下是我从下载节点程序得到的数据:
[
"uri": "https://storage.googleapis.com/jtg_app_bucket/device_6/image.jpg" ,
"uri": "https://storage.googleapis.com/jtg_app_bucket/device_6/loved_it.jpg"
]
我需要像在上传节点程序中那样使用 resolve(data) 发送数据,但我无法做到这一点。谁能建议如何做到这一点?提前致谢。
我正在控制台中获取 const 数据中的数据,我想将其在 resolve() 中发送回 index.js 中的 /file_download。在 Postman 中,当我运行“http://localhost:9001/file_download”时,出现以下错误:
"error": ,
"message": "Internal server error!"
我希望输出为
"message": "Download Successful",
"data": [
"uri": "https://storage.googleapis.com/jtg_app_bucket/device_6/image.jpg" ,
"uri": "https://storage.googleapis.com/jtg_app_bucket/device_6/loved_it.jpg"
]
这样我就可以使用它在 React Native App 中显示图像。希望这很清楚。
【问题讨论】:
请不要使用图片来传达代码或错误信息。 Here's why. 是的..我编辑了这个问题。 您能否描述一下与您的预期结果相比的实际结果?看起来你有一些代码试图做你想做的事。所以发生了什么事?什么地方出了错?为什么你“做不到”? 我在上面的问题中补充了几点,我打算做什么。谢谢 我建议您在有catch (error)
的地方添加代码以立即执行console.error(error)
,这样您就可以看到异常是什么。
【参考方案1】:
我刚刚从 downloadhelpers.js 中删除了最后三行,它工作正常。
下面是正确的下载节点。
下载helpers.js
module.exports = downloadImage = (FolderToDisplay) => new
Promise((resolve, reject) =>
const folder_name = FolderToDisplay;
const Storage = require('@google-cloud/storage');
var projectId = 'vast-service-281617' // Your Google Cloud Platform
project ID
var keyFilename = './../UploadPhotosNode/config/keys.json'
const storage = new Storage(keyFilename,projectId);
var bucket = storage.bucket("gs://jtg_app_bucket");
const bucketName = 'jtg_app_bucket';
// The directory prefix to search for
const prefix = folder_name+'/';
// The delimiter to use
const delimiter = '/';
const options =
prefix: prefix,
;
bucket.getFiles(options).then(results =>
const files = results[0];
var resData =
success: true,
images:
/* id:[], */
results: []
;
files.forEach(file =>
resData.images.results.push(
uri:'https://storage.googleapis.com/'+bucketName+'/' +file.name);
)
var stringified = JSON.stringify(resData);
var only_images = JSON.parse(stringified);
const data = only_images.images.results;
console.log(data);
resolve(data)
)
)
下面是 Postman 的结果:
"message": "Download Successful",
"data": [
"uri":
"https://storage.googleapis.com/jtg_app_bucket/device_6/image.jpg"
,
"uri":
"https://storage.googleapis.com/jtg_app_bucket/device_6/loved_it.png"
]
【讨论】:
以上是关于将数据从 Node.js 发送回客户端的主要内容,如果未能解决你的问题,请参考以下文章
c# SocketIoClientDotNet, node js socket.IO
将数据从服务器(Node.js)发送到 GraphQL 服务器中的客户端(React 组件)