如何在Nuxt.js中配置本地8080端口API的代理访问?
Let's walk through the issues in your setup and fix them step by step:
1. Ensure @nuxtjs/axios is Properly Configured
First, make sure you've installed the official Nuxt axios module and added it to your config. If you haven't, run this command:
npm install @nuxtjs/axios
Then update your nuxt.config.js to include it in the modules array:
modules: [ '@nuxtjs/axios', ],
2. Correct Your Proxy Configuration
Your current proxy setup is rewriting the /api path, which sends requests to the wrong endpoint on your backend. Since your backend API lives under http://localhost:8080/api/, we need to preserve that /api segment. Here's the fixed proxy config:
axios: { proxy: true, // If your Nuxt app is served at http://localhost:3000/restapi/, set the baseURL here baseURL: process.env.BASE_URL || 'http://localhost:3000/restapi/' }, proxy: { '/api/': { target: 'http://localhost:8080/', changeOrigin: true, // This fixes most CORS-related issues // Remove the pathRewrite line - we don't want to strip /api from the request prependPath: true // Default is true, optional but explicit } }, // If your Nuxt app is hosted under the /restapi/ route, add this router config router: { base: '/restapi/' },
3. Update Your Component to Use Nuxt's Axios Instance
Stop importing axios directly - Nuxt provides a pre-configured $axios instance that works seamlessly with the proxy. Also, use the relative path instead of the full backend URL so the proxy kicks in:
<template> <div class="container"> {{ docbases }} </div> </template> <script> // No need to import axios here! export default { async asyncData({ $axios, error }) { try { // Use the relative path to leverage the proxy const { data } = await $axios.get('/api/dfc/system/docbases'); return { docbases: data }; } catch (e) { error({ statusCode: 404, message: 'Could not fetch docbases' }); } }, head: { title: "D2Rest" } }; </script>
4. Quick Checks to Rule Out Other Issues
- Confirm your backend at
http://localhost:8080/api/dfc/system/docbasesstill returns["gr_swy","SubWayX_DEMO"]when accessed directly. - Open your browser's dev tools Network tab to verify the client is requesting your Nuxt server (e.g.,
http://localhost:3000/restapi/api/dfc/system/docbases) instead of the backend directly.
This setup should now correctly proxy your requests from Nuxt to your backend API, bypassing CORS issues and fetching the data you need.
内容的提问来源于stack exchange,提问作者this.srivastava

