小程序支付api密鑰
問題 (The Problem)
All you want to do is fetch some JSON from an API endpoint for the weather, some book reviews, or something similarly simple.
您要做的就是從API端點獲取一些有關天氣的JSON,一些書評或類似的簡單內容。
The fetch query in your front-end is easy enough, but you have to paste your secret API key right there in the front-end code for anybody to find with a trivial amount of digging!
前端中的獲取查詢非常容易,但是您必須在前端代碼中將您的秘密API密鑰粘貼到前端代碼中,以便任何人都能通過少量的挖掘找到它!
Also, pushing your API keys to your GitHub repository is a major problem: Dev put AWS keys on Github. Then BAD THINGS happened.
另外,將API密鑰推送到GitHub存儲庫也是一個主要問題: Dev將AWS密鑰放在Github上。 然后發生了壞事 。
"Why is this so hard?!" – You, probably 15 minutes ago
“為什么這么難?!” –您,大約15分鐘前
解決方案 (The Solution)
You should use a back-end server as a relay to fetch the API results for you and then pass them on to your front-end
您應該使用后端服務器作為中繼來為您獲取API結果,然后將其傳遞給您的前端
新問題 (The New Problem)
You're just trying to do a front-end demo for your portfolio! You haven't learned anything about back-end technologies yet! Why is this so hard?!
您只是想為您的投資組合做一個前端演示! 您尚未了解有關后端技術的任何信息! 為什么這么難?!
演示版 (Demo)
I've encountered this problem often enough that I've decided to stop coming up with silly hacks and implement a solution that works with minimal back-end code.
我經常遇到此問題,以至于我決定停止提出愚蠢的駭客,并實施一個使用最少的后端代碼的解決方案。
In this demo I set up a back-end that listens for POST requests and sends them to the GoodReads API. To use this you need to implement your own front-end that can send the appropriate POST request to this back-end. Your front-end won't communicate with GoodReads directly, so no API key is exposed.
在此演示中,我設置了一個后端,用于偵聽POST請求并將其發送到GoodReads API 。 要使用此功能,您需要實現自己的前端,該前端可以將適當的POST請求發送到此后端。 您的前端不會直接與GoodReads通信,因此不會暴露任何API密鑰。
你會需要 (You will need)
Node (this has been tested with v10.16.0, later versions will be fine, earlier ones may encounter problems)
節點 (已通過v10.16.0進行了測試,以后的版本會很好,早期的版本可能會遇到問題)
git
吉特
- This repo: https://github.com/JacksonBates/example-goodreads-api-relay 這個倉庫:https://github.com/JacksonBates/example-goodreads-api-relay
開始吧 (Get started)
git clone https://github.com/JacksonBates/example-goodreads-api-relay.git
git clone https://github.com/JacksonBates/example-goodreads-api-relay.git
The README.md contains everything you should need to know, including installation and set up.
README.md包含您需要了解的所有內容,包括安裝和設置。
I've included the key points here for convenience:
為了方便起見,我在此處列出了關鍵點:
自述文件 (README.md)
Install dependancies:
安裝依賴關系:
npm i
npm i
You need to create your own .env
file for your key:
您需要為密鑰創建自己的.env
文件:
cp .env.example .env
cp .env.example .env
Then open the new .env
file and paste your keys in the correct spot.
然后打開新的.env
文件,然后將密鑰粘貼到正確的位置。
Example:
例:
GOODREADS_API_KEY=AABBCCDDEEFF00112233445566778899
Now run the server:
現在運行服務器:
node app.js
node app.js
In the browser, navigate to localhost:3000 to confirm the server is running. You should see a simple Hello World!
在瀏覽器中,導航到localhost:3000以確認服務器正在運行。 您應該會看到一個簡單的Hello World!
接下來是什么? (What next?)
Now read the app.js
file thoroughly.
現在,徹底閱讀app.js
文件。
I've commented the code heavily to help you understand what is going on if you haven't seen node / express much before.
我對代碼進行了重注釋,以幫助您了解以前沒有多少節點/表達式的情況。
// app.js// These import necessary modules and set some initial variables
require("dotenv").config();
const express = require("express");
const fetch = require("node-fetch");
const convert = require("xml-js");
const rateLimit = require("express-rate-limit");
const app = express();
const port = 3000;// Rate limiting - Goodreads limits to 1/sec, so we should too// Enable if you're behind a reverse proxy (Heroku, Bluemix, AWS ELB, Nginx, etc)
// see https://expressjs.com/en/guide/behind-proxies.html
// app.set('trust proxy', 1);const limiter = rateLimit({windowMs: 1000, // 1 secondmax: 1, // limit each IP to 1 requests per windowMs
})// apply to all requests
app.use(limiter)// Routes// Test route, visit localhost:3000 to confirm it's working
// should show 'Hello World!' in the browser
app.get("/", (req, res) => res.send("Hello World!"));// Our Goodreads relay route!
app.get("/api/search", async (req, res) => {try {// This uses string interpolation to make our search query string// it pulls the posted query param and reformats it for goodreadsconst searchString = `q=${req.query.q}`;// It uses node-fetch to call the goodreads api, and reads the key from .envconst response = await fetch(`https://www.goodreads.com/search/index.xml?key=${process.env.GOODREADS_API_KEY}&${searchString}`);//more info here https://www.goodreads.com/api/index#search.booksconst xml = await response.text();// Goodreads API returns XML, so to use it easily on the front end, we can// convert that to JSON:const json = convert.xml2json(xml, { compact: true, spaces: 2 });// The API returns stuff we don't care about, so we may as well strip out// everything except the results:const results = JSON.parse(json).GoodreadsResponse.search.results;return res.json({success: true,results})} catch (err) {return res.status(500).json({success: false,message: err.message,})}
})// This spins up our sever and generates logs for us to use.
// Any console.log statements you use in node for debugging will show up in your
// terminal, not in the browser console!
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
Update: Huge thanks to Gouri Shankar Kumawat for contributing a PR that improved this code! You can follow him on Twitter at @dev_gskumawat, or on GitHub: gskumawat0
更新 :非常感謝Gouri Shankar Kumawat貢獻了改進此代碼的PR! 您可以在Twitter上@dev_gskumawat或在GitHub上關注他: gskumawat0
測試API中繼 (Test the API relay)
Use Postman to test the API.
使用Postman測試API。
Set Postman to GET and paste this in the url: localhost:3000/api/search?q=hobbit
將Postman設置為GET并將其粘貼在url中: localhost:3000/api/search?q=hobbit
Postman will show you the JSON response below.
郵遞員將在下面顯示JSON響應。
您如何在前端使用它? (How do you use this in your front end?)
This simple app is listening for post requests at /api/search
, so interact with it in your front end app the way you have been previously with the original api.
這個簡單的應用程序正在/api/search
監聽發布請求,因此可以像以前使用原始api的方式在前端應用程序中與之交互。
This is only configured to handle search queries - if you want to use other Goodreads API endpoints / methods, you'll need to think about how you implement them yourself!
它僅配置為處理搜索查詢-如果您想使用其他Goodreads API端點/方法,則需要考慮如何自己實現它們!
代管 (Hosting)
You can't deploy your front-end and still have this on localhost - obviously you need to deploy this, too.
您無法部署前端,而仍在本地主機上擁有它-顯然您也需要部署它。
I recommend Heroku.
我推薦Heroku 。
額外信用 (Extra Credit)
If you wanted to extend this, you could consider how you might only make this accessible from a restricted range of IP addresses to increase the security - which was outside of the scope of this tutorial / demo.
如果要擴展此功能,可以考慮如何僅允許從有限的IP地址范圍訪問此地址,以提高安全性-這超出了本教程/演示的范圍。
This was hastily put together in response to a discussion on the forum. If you spot any issues in this post or the example code, please don't hesitate to reply to the forum thread that started it all. I'll keep the article and repo up-to-date with improvements.
這是為了響應論壇上的討論而匆忙進行的。 如果您發現本文或示例代碼中有任何問題,請隨時回復啟動所有內容的論壇主題 。 我將繼續撰寫本文,并回購最新的改進內容。
Feel free to submit PRs if you have valuable contributions to make :)
如果您有寶貴的貢獻,請隨時提交PR:
You can also reach out to me via Twitter: @JacksonBates.
您也可以通過Twitter: @JacksonBates與我聯系 。
翻譯自: https://www.freecodecamp.org/news/private-api-keys/
小程序支付api密鑰