我正在尝试在 React 应用程序中包含街景图像。以下是 API 的文档: Street View Static API
当我向 google 发出一个简单的 fetch 请求时,我收到一个响应,其中包含街景图像的 URL 作为 JPG 文件:
bodyUsed:false
headers:Headers
ok:true
redirected:false
size:0
status:200
statusText:"OK"
Symbol(Body internals):Object {body: PassThrough, disturbed: false, error: null}
Symbol(Response internals):Object {url: "https://maps.googleapis.com/maps/api/streetview?lo…", status: 200, statusText: "OK", …}
timeout:0
// URL BELOW HERE IS WHAT I'M USING
url:"https://maps.googleapis.com/maps/api/streetview?location=3737%20N%20Southport%20Ave,%20Chicago,%20IL%2060613&key={MY_SECRECT_KEY}&size=300x300"
我不能直接在我的应用程序中使用此图像 URL,因为它包含我的秘密 API 密钥。
我现在尝试做的是使用 AWS lambda 函数,该函数使用 Node 从 URL 读取图像文件,然后将此图像文件作为 HTTP 响应发送到客户端的反应应用程序。
我无法弄清楚如何在 Node.js 中执行此操作。我在网上看到了一些关于在文件系统模块中使用 Node 的readFile 函数的代码。但我无法让它工作。
这是我的 Lambda 函数中的代码:
const fetch = require('node-fetch');
const fs = require('fs');
const autoCompURL = "https://maps.googleapis.com/maps/api/streetview?"
const { G_PLACES_KEY } = process.env
const key = `&key=${G_PLACES_KEY}`
const size = "&size=300x300"
function getSearch(e) {
const resp = JSON.parse(e.body)
return resp.place_address
}
async function googleResults(str) {
const response = await fetch(
`${autoCompURL}location=${str}${key}${size}`
)
return new Promise(resolve => resolve(response));
}
exports.handler = async function(event, context) {
try {
const userSearch = getSearch(event)
const autoResults = await googleResults(userSearch)
const imgURL = autoResults.url
const img = await fs.promises.readFile(imgURL)
if (autoResults.status !== "OK") {
// NOT res.status >= 200 && res.status < 300
return { statusCode: autoResults.status, body: autoResults.statusText, error_message: autoResults.error_message }
}
return {
statusCode: 200,
headers: {'Content-Type': 'image/jpeg'},
body: img
}
} catch (err) {
console.log(err) // output to netlify function log
return {
statusCode: 500,
body: JSON.stringify({ msg: err.message }) // Could be a custom message or object i.e. JSON.stringify(err)
}
}
}
感谢任何关于我如何让它发挥作用的线索。