【发布时间】:2022-10-24 22:10:31
【问题描述】:
我使用 NextJS API 路由基本上只是代理使用 Python 和 Django 构建的自定义 API,但尚未完全公开,我使用 Vercel 上的教程将 cors 作为中间件添加到路由但它没有提供确切的我想要的功能。
我不想让任何人向路由发出请求,这种方式违背了目的,但它至少仍然隐藏了我的 API 密钥。
问题
有没有更好的方法来正确停止从外部来源对路由发出的请求? 任何答案表示赞赏!
// Api Route
import axios from "axios";
import Cors from 'cors'
// Initializing the cors middleware
const cors = Cors({
methods: ['GET', 'HEAD'],
allowedHeaders: ['Content-Type', 'Authorization','Origin'],
origin: ["https://squadkitresearch.net", 'http://localhost:3000'],
optionsSuccessStatus: 200,
})
function runMiddleware(req, res, fn) {
return new Promise((resolve, reject) => {
fn(req, res, (res) => {
if (res instanceof Error) {
return reject(res)
}
return resolve(res)
})
})
}
async function getApi(req, res) {
try {
await runMiddleware(req, res, cors)
const {
query: { url },
} = req;
const URL = `https://xxx/api/${url}`;
const response = await axios.get(URL, {
headers: {
Authorization: `Api-Key xxxx`,
Accept: "application/json",
}
});
if (response.status === 200) {
res.status(200).send(response.data)
}
console.log('Server Side response.data -->', response.data)
} catch (error) {
console.log('Error -->', error)
res.status(500).send({ error: 'Server Error' });
}
}
export default getApi
【问题讨论】: