Nuxt3 问题求解

2023-02-20 19:33:01 +08:00
 PEax

最近没事在学习 nuxt

前端为 Nuxt3 写的,开启 SSR

后端为 Node 写的服务

nuxt.config.ts文件中设置代理

nitro: {
    devProxy: {
      '/api/': {
        target: 'http://127.0.0.1:3001/api/',
        changeOrigin: true
      }
    }
  },

在 nuxt3 项目页面中使用$fetch('/api/xxx') 可以使用且正确返回

在 middleware 中间件(不是 server 的中间件)做拦截,需要请求接口判断一些东西

export default defineNuxtRouteMiddleware(async (to, from) => {
	const result = await $fetch('/api/config/info')
  // $fetch('http://127.0.0.1:3001/api/config/info') 这样写全链接就能访问到
})

在中间件请求$fetch('/api/config/info') 会提示 404 Page not found (似乎是把这样的接口认为是项目本身的页接口了),使用全链接接口能正常返回,但是我发现部署到服务器之后,他是在前端发起的请求?为什么,不是服务端渲染后返回的吗?

问:

1041 次点击
所在节点    前端开发
1 条回复
maplezzz
2023-02-20 20:51:46 +08:00
1. 看文档,middleware 在初始页就是会被调用两次的,server 端一次,client 端一次
> If your site is server-rendered or generated, middleware for the initial page will be executed both when the page is rendered and then again on the client.

2. 可以把 fetch 封装一下,prod 环境请求时拼上 api 的前缀

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/917730

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX