配置跨域
本地的反向代理我们可以通过Nitro引擎来配置
服务器请求没有跨域,也就不需要配置代理转发
export default defineNuxtConfig({
nitro: {
devProxy: {
"/commonApi": {
target: "https://www.blockxu.com",
changeOrigin: true,
},
...
}
}
})
接口封装
nuxt3中虽然也可以使用axios,但nuxt本身对fetch做了封装,并提供了几个函数
这几个方法是SSR友好组合,在服务端和客户端都可以使用,并且可以防止接口在服务端和客户端重复调用浪费性能
// 接口封装
export function serverRequest(url,data) {
...
let name = obj.url + JSON.stringify(data);
...
const options = {
...obj,
onRequest({ request, options }) {...},
onResponse({ request, response, options }) {...},
};
// 发起请求
return useAsyncData(name, () => $fetch(url, options), config);
}
...
// 使用
const { data, status, error } serverRequest('http://www.blockxu.top')
接口封装可以看我的另一篇博客
推荐用法
更推荐使用useFetch直接在业务中请求数据,将返回的数据直接当做ref使用
<template>
<div>{{data}}</div>
</template>
<script setup>
import { api } from "~/api/index";
const headers = useRequestHeaders(["cookie"]);
const { data, status, error } = await useFetch(api.login, {
method: "post",
headers: {
...headers,
},
});
...
</script>

本文介绍了如何在Nuxt.js中通过Nitro引擎配置本地反向代理处理跨域问题,同时探讨了Nuxt的fetch封装方法(如useFetch)以及其在服务端渲染(SSR)中的优势。作者还推荐了在业务代码中使用useFetch进行接口调用的最佳实践。


1597

被折叠的 条评论
为什么被折叠?



