node.js - 使用来自 Google Street View Static API 的图像而不暴露密钥
问题描述
我正在尝试在 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)
}
}
}
感谢任何关于我如何让它发挥作用的线索。
解决方案
你试过这个选项吗?
您可以生成数字签名并将其与 API 调用一起使用。并将未签名的请求限制为零。
推荐阅读
- wpf - 如果您只有对 Binding 对象的引用,而不是它所绑定的对象,是否可以手动刷新绑定?
- php - VerifyCsrfToken.php 第 68 行中的 TokenMismatchException:Laravel 5.3
- java - Mongodb java:具有通用字段的 Perist POJO 类
- rest-assured - 无法使用 RestAssured 触发多部分请求
- docker - 如何为 docker-compose 和 kubernetes 使用相同的 nginx.conf 文件进行反向代理
- php - 将电子表格解析为 PHP 数组并返回具有父子关系的嵌套 MLM 表
- c# - LINQ 查询:从一组对象聚合子集
- extjs - 将负载掩码应用于选项卡面板时面临问题
- java - Spark JAVA程序
- html - 如何正确对齐菜单三明治 bootsrap 4