V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
PEax
V2EX  ›  前端开发

Nuxt3 问题求解

  •  
  •   PEax · 2023-02-20 19:33:01 +08:00 · 942 次点击
    这是一个创建于 444 天前的主题,其中的信息可能已经有所发展或是发生改变。

    最近没事在学习 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 (似乎是把这样的接口认为是项目本身的页接口了),使用全链接接口能正常返回,但是我发现部署到服务器之后,他是在前端发起的请求?为什么,不是服务端渲染后返回的吗?

    问:

    • 如何在中间件中请求 API ?
    • 写 /api/xxx 部署到服务器运行的时候,会提示 No match found for location with path ,说是本地运行的接口
    • 能不能像正常的前端项目那样,本地起代理服务器 /api 转发代理到本地方便调试、部署项目到服务器时匹配 /api 而不会报 404 Page not found 的错误?
    1 条回复    2023-02-20 20:51:46 +08:00
    maplezzz
        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 的前缀
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1814 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 16:29 · PVG 00:29 · LAX 09:29 · JFK 12:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.