如何在Nuxt3中设置代理?

问题描述 投票:0回答:4

我尝试启动一个nuxt3程序,现在我想设置服务器代理。 对 http://localhost:3000/api/v1 的请求应该会从我们的后端服务器返回响应 http://39.98.58.238:8594 ,但现在它给了我一个 404 页面。

首先,我按照 vite.js 文档设置 nuxt.config.js 文件

nuxt.config.js

export default defineNuxtConfig({  
  ...  
  vite: {
    server: {
      proxy: {
        '/api': {
          target: 'http://39.98.58.238:8594',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      },
    }
  },
})

<script setup>
  async function test() {
   await usefetch('/api/v1/xxx')
  }
</script>
<template>
  <div>
    <button @click="test">check</button>
  </div>
</template>

没用,我的请求返回了404页面。 然后我尝试遵循这个问题:text,不要使用vite代理

nuxt.config.js

export default defineNuxtConfig({
  nitro: {
    devProxy: {
        '/api/': {
            target: 'http://39.98.58.238:8594/',
            changeOrigin: true
        }
    }
  }
})

但是还是不行。我可以做什么来解决这个问题?谢谢!!!

vue.js proxy nuxt.js vite nuxtjs3
4个回答
10
投票

对于那些仍然想知道如何在生产模式中执行此操作的人。我相信答案是

export default defineNuxtConfig({
  nitro: {
    routeRules: {
      '/proxy/example': { proxy: 'http://39.98.58.238:8594' },
      "/proxy/**": { proxy: '/api/**' },
    }
  }
})

您可以在这里找到文档⚠️实验!


4
投票
   export default defineNuxtConfig({  
        nitro: {
            devProxy: {
                "/devApi": {
                    target:"your url",
                    changeOrigin: true,
                    prependPath: true,
                }
            }
        },
    })

1
投票

对于你的例子来说,应该是

export default defineNuxtConfig({
    nitro: {
        devProxy: {
            '/api': {
                target: 'http://39.98.58.238:8594/api',
                changeOrigin: true
            }
        }
    }
})

检查对象键“/api”和“target: '..../api'”属性。


0
投票

Nuxt v3.11

.env

API_URL="https://example.com/api/**"

env.d.ts

/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly API_URL: string;
}

interface ImportMeta {
  readonly env: ImportMetaEnv;
}

nuxt.config.ts

export default defineNuxtConfig({
  devtools: { enabled: true },
  routeRules: {
    "/api/**": { proxy: import.meta.env.API_URL },
  },
});
© www.soinside.com 2019 - 2024. All rights reserved.