我正在学习使用 Node (Express) + React 构建一个天气应用程序。我成功从开放天气 API 获取了天气数据。
但是,我在 React 应用程序中直接使用开放天气 API key ,如下所示 const WeatherURL = 'http://api.openweathermap.org/data/2.5/weather?q=london,uk&APPID=1234567qwerty' ;
。显然这是不安全的,因为它向客户端暴露了 API key 。我考虑过将 API key 存储在 .env
文件中,但根据 [this answer][1],我永远不应该将 API key 存储在 .env
文件或 .gitignore
。正确的方法是向后端API发出请求,然后向后端调用API并将数据发送回来。我不知道该怎么做。有人可以帮忙吗?
以下是我的 Node.js 代码:
const express = require('express');
const cors = require('cors');
const app = express();
const SELECT_ALL_QUERY = 'SELECT * FROM `mySchema`.`myTable`;';
app.use(cors());
app.get('/', (req, res) => {
res.send('go to /myTable to see content')
});
const pool = require('./awsPool');
pool.getConnection((err, connection) => {
if (err) {
return console.log('ERROR! ', err);
}
if(!connection) {
return console.log('No connection was found');
}
app.get('/myTable', (req, res) => {
console.log(connection);
connection.query(SELECT_ALL_QUERY, (err, results) => {
if (err) {
return res.send(err)
}
else {
return res.json({
data: results
})
};
});
});
});
let port=process.env.PORT||4000;
app.listen(port, () => {
console.log(`App running on port ${port} `);
});```
[1]: https://stackoverflow.com/a/57103663/8720421
最佳答案
链接的答案建议的是在 Node/Express 后端 API 中创建一条路线,该路线将为您调用天气 API,而不是前端。这样,每当您的前端进行调用时,请求和您的 API key 都不会面向公众。
执行此操作的方法本质上与您在 React 中所做的相同,即使用内置或第 3 方库发出 HTTP 请求。 This resource我刚刚发现有一些关于如何同时执行这两项操作的信息。
关于node.js - 如何使用node js从后端API请求apikey?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63024229/