我正在创建一个新的 Nuxt3 项目,在其中调用第三方 API,它使用 x-api-key 来获取数据。
如何保护我的 x-api-key?就像在 Nuxt3 JS 中使用中间件或其他东西
API 在 PostMan 上工作正常,但从项目调用时会出现 CORS 错误。
这绝对是一种常见做法,并非 Nuxt 特有的,但您可以在 Nuxt 3 中执行此操作。如果您想完全避免将第三方 API 密钥暴露给前端,您需要保留该 API从
public
中 runtimeConfig
的 nuxt.config.ts
部分键入,并从前端可以调用的 Nitro 服务器端点 访问它。
// nuxt.config.ts
export default defineNuxtConfig({
...
runtimeConfig: {
thirdPartyApiKey: 'somekindofkeythatsprivate',
...
public: { // values here are exposed to the frontend },
},
});
// server/api/thirdparty.ts
export default defineEventHandler(async (event) => {
// Grab the api key from runtime config
const { thirdPartyApiKey } = useRuntimeConfig();
// Make a call to the api with the key included as the 'X-API-KEY' header
const response = await $fetch('https://thethird.party/api/some/endpoint/', {
headers: { 'X-API-KEY': thirdPartyApiKey },
});
// return the result of passing the response to some composable that does
// internal logic of some kind
return useSomeKindOfInternalLogic(response);
});
// pages/index.ts
<template>
<div>{{ data }}</div>
</template>
<script setup lang="ts">
const data = $fetch('/api/thirdparty');
</script>
注意: 您可能需要考虑以某种方式锁定此 /api/thirdparty
端点,因为即使您已从前端/消费者隐藏了 api 密钥,该端点仍然可以从任何地方调用,而不仅仅是从您的前端组件。