[英]Make get request to third party API with api key using express.router();
我正在構建一個 React 應用程序,並在其中從第三方站點檢索數據,該站點要求我使用“X-Auth-Token”在標頭中發送 API 密鑰。
目前,我正在使用客戶端 js 文件中的 fetch() api 發出此請求。 我知道這是不好的做法,我應該隱藏我的 api 密鑰,所以這就是我想要做的,但我發現很難理解所有組件如何在這個謎題中組合在一起......
我遵循了一個教程,現在有一個 create-react-app 項目在端口 3000 上本地偵聽,以及一個快速服務器(使用 express.router())在端口 9000 上本地偵聽。
我想從快遞服務器向第三方發出api請求,然后將其發送到前端。
您說得對,您應該像中間人一樣使用將數據檢索到前端。 當然有幾個實現。 我個人喜歡無服務器方法,使用 AWS lambda 函數。 但是回到你的方法。 我可能會使用 axios 模塊檢索數據,非常簡單明了。 您可以將 x-auth-token 標頭傳遞給實例
const express = require('express');
const axios = require('axios');
const app = express()
const axiosInstance = axios.create({
baseURL: '<some-domain>',
headers: { 'X-Auth-Token' : '<some-token>'}
});
app.get('/data', async(req, res, next) => {
try {
const response = await axiosInstance.get('/<path>');
// process your data and send back to the user
} catch (error) {
// handle if you got an error
}
})
這只是一個展示,我假設您的應用程序看起來不同,但我認為您從這個片段中得到了一些指導。
我會將令牌隱藏到環境變量中。
當您將服務器部署到 heroku 時,您將獲得一個 url,在您的前端,您可以輕松替換該 url 並進行部署。
在這兩種情況下,環境變量都會為您提供幫助。 您可以使用dotenv庫。 代碼示例經過簡化以專注於您的問題。
require('dotenv').config(); // init env vars
const got = require('got');
const express = require('express');
const router = express.Router();
// getting API key from env variable
const apiKey = process.env.AUTH_KEY;
// GET localhost:9000/endpoint
router.get('/endpoint', async (req, res) => {
// requesting data from 3rd party service
const response = await got('https://thirdpartyservice.com/api', {
headers: {
'x-auth-token': apiKey, // the auth token header
json: true, // assuming response will be "application/json"
},
});
// passing data to React
res.json(JSON.parse(response));
});
發展:
# .env file on your localhost
AUTH_KEY = <your_secret_key>
API_URL=localhost:9000/
生產:
# env vars on heroku
AUTH_KEY = <your_secret_key>
API_URL=<api_server_name>.herokuapp.com/
並將 URL 傳遞給您的 React 應用程序:
require('dotenv').config(); // init env vars
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
// your api server URL from env vars
const apiUrl = process.env.API_URL;
// pass the api URL to your React app
ReactDOM.render(
<App apiUrl={ apiUrl } />,
document.getElementById('root'),
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.