问题答案 12026年7月5日 09:38
How to set proxy for different API server using Nuxt?
In Nuxt.js, to address cross-origin request issues or to route API requests to different servers, we can utilize the built-in proxy module or configure custom proxy rules. This is achieved by setting up the property in the file. Here are the steps to implement this:Installing DependenciesFirst, ensure the module is installed. If not, install it using:Or with :ConfiguringThen, in your file, add to the section and configure the property. For example:In this example:Requests targeting the path are forwarded through the proxy to . The property ensures the segment is removed from the request path during forwarding.Requests for the path are forwarded to , with similarly removing the segment.Setting to instructs the proxy to modify the header in request headers to reflect the target server's hostname, which is commonly required for backend APIs that enforce hostname checks.By doing this, you can define multiple proxy rules based on different paths to forward requests to distinct API servers.Using Proxies in DevelopmentDuring local development, you can directly make requests to or paths via the Nuxt.js service. These requests are automatically forwarded to the respective target servers without cross-origin concerns.Production EnvironmentWhen deploying to production, ensure the relevant proxy services are correctly configured so the proxy rules remain effective.Example:Suppose your Nuxt.js application fetches data from different sources, such as:User data from Product data from Your proxy configuration might look like this:After this setup, requests to in your Nuxt.js application are proxied to the user API server, and requests to are proxied to the product API server.