Nuxt3 实现接口域名动态化

为什么要做接口动态?

  • 多个域名指向同一个项目, 比如www.abc.con和abc.com都指向同一个项目, 写死前缀会出现跨域问题
  • 小公司没有运维, Nginx配置不太熟悉
  • 之前项目的接口前缀一直是通过不同的.env文件配置好的. 想实现下动态化

此时可以通过前端项目实现接口域名动态-根据网站域名来处理, 避免接口跨域

怎么实现?

1, 创建环境配置 .env.developmen和.env.production

ini 复制代码
// .env.developmen (本地开启代理使用)
NUXT_PUBLIC_API_BASE = /api
arduino 复制代码
// .env.production
NUXT_PUBLIC_API_BASE = //www.abc.com

2, 在 nuxt.config.ts 中增加配置, 将环境配置信息加入到项目运行配置中

arduino 复制代码
export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      apiBase: process.env.NUXT_PUBLIC_API_BASE,
    }
  },
})

3, 创建plugins文件夹及下面的api-domain.ts

typescript 复制代码
/**
 * 接口域名 根据网站域名一致
 * 客户端获取域名, 接口请求时使用
 */
import { defineNuxtPlugin } from '#app'

export default defineNuxtPlugin((nuxtApp: any) => {
  // 客户端获取域名
	if (process.client) {
    // 获取项目运行时的配置
      const config = useRuntimeConfig()
    // 获取配置的接口前缀
      const apiBase = config.public.apiBase
    let currentDomain = ''
    // 非本地运行, 协议和域名拼接下
		if (apiBase !== '/api') {
			currentDomain = window.location.protocol + '//' + window.location.host
		} else {
      // 本地运行
      currentDomain = apiBase
    }
    // 注入到项目中
    nuxtApp.provide('apiDomain', currentDomain)
	}
})

4, 组件中使用

xml 复制代码
<script setup lang="ts">
import { useNuxtApp } from '#app';
const nuxtApp = useNuxtApp();
const apiDomain = nuxtApp.$apiDomain;


const getList = async () => {
	try {
		const response = await $fetch(
			`${apiDomain}/getList/abc/111`,
			{
				method: 'POST',
			}
		)
    console.log(response)
		
	} catch (error) {
		console.log(error)
	}
}

onMounted(() => {
	getList()
})
</script>

<template>
</template>

<style scoped>
</style>
相关推荐
JavaGuide21 分钟前
刚刚,阿里版 Codex 上线了匿名模型 HungerG,无限 Token!
前端·后端
zhanlang021730 分钟前
HTML 零基础入门到企业实战全套教程【第九章 9.3】移动端 HTML 基础适配入门
前端·html
用户693717500138437 分钟前
AI 帮我写了大半年的代码,我却越来越不会写代码了
前端·后端·github
skywalk81631 小时前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness
彭亚川Allen1 小时前
从零手搓 RAG:用 Elasticsearch 存储与检索向量
前端·后端·面试
jerrywus1 小时前
15 个可以直接安装的 AI Agent Skills:按场景挑
前端·agent·claude
涛涛ing1 小时前
用了三年微前端,我们终于把它拆成了单体应用
前端
去伪存真2 小时前
《最终版》《打死不改版》全传一遍?RAG 系统文件去重实战
前端
anyup2 小时前
【全端支持】 uni-app x 专用请求库:axios 写法,多实例、拦截器、可中断、上传下载
前端·uni-app·unix
费曼学习法2 小时前
6 个 MCP Server 传输层重写实录:超时率 12% → 0.3%
前端·后端