Nuxt3 实现接口域名动态化

178 阅读1分钟

为什么要做接口动态?

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

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

怎么实现?

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

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

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

export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      apiBase: process.env.NUXT_PUBLIC_API_BASE,
    }
  },
})

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

/**
 * 接口域名 根据网站域名一致
 * 客户端获取域名, 接口请求时使用
 */
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, 组件中使用

<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>