【问题标题】:How to block external requests to a NextJS Api route如何阻止对 NextJS Api 路由的外部请求
【发布时间】: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

【问题讨论】:

    标签: django next.js


    【解决方案1】:

    对不起,这个迟到的答案,

    我只是认为这是 NextJS 的默认行为。你已经准备好了,别担心。相反,如果您想允许外部资源获取您的 Next API,则需要进行一些自定义

    【讨论】:

      猜你喜欢
      • 2016-09-11
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 2022-01-09
      • 2012-05-25
      • 2020-10-30
      相关资源
      最近更新 更多