乐闻世界logo
搜索文章和话题

How to set baseURL in dev or production in Nuxtjs?

1个答案

1

Nuxt.js is a framework built on Vue.js for developing server-rendered applications (SSR), static sites (SSG), or single-page applications (SPA). In Nuxt.js, you can configure baseURL by setting environment variables, which serves as the base path for API requests.

In a Nuxt.js project, you can configure baseURL in two locations:

  1. nuxt.config.js: This is the location for setting project-level configuration. You can define a default baseURL here, which applies to both development and production environments, but it can be overridden by environment variables.
  2. Environment Variables: Use .env files or environment variables directly to set baseURL, enabling different values for various environments (development, production, etc.).

Setting baseURL in nuxt.config.js

You can define baseURL by setting the baseURL option in the axios module within the nuxt.config.js file. This module automatically injects baseURL into the axios instance used throughout the application.

javascript
export default { // ... axios: { // Base URL for API server baseURL: process.env.BASE_URL || 'http://localhost:3000' }, // ... }

In the above example, process.env.BASE_URL is an environment variable that you can set in your project's .env file or directly in the command line. If BASE_URL is not set, it defaults to 'http://localhost:3000' as the fallback value.

Setting baseURL via .env File

Create a .env file in the root directory of your project and set the BASE_URL environment variable:

shell
BASE_URL=https://api.example.com

Next, install the @nuxtjs/dotenv module to enable Nuxt.js to read the .env file:

bash
npm install @nuxtjs/dotenv

Then, include this module in your nuxt.config.js file:

javascript
require('dotenv').config(); export default { modules: [ '@nuxtjs/dotenv', ], // ... axios: { baseURL: process.env.BASE_URL }, // ... }

Setting Environment Variables at Runtime

In development mode, you can set environment variables when starting the Nuxt.js server:

bash
BASE_URL=https://api.example.com nuxt

In production mode, if using a process manager like PM2, set environment variables when starting the application:

bash
BASE_URL=https://api.example.com pm2 start npm --name "my-app" -- run start

Alternatively, set environment variables in your production deployment script.

Ensure you follow security and best practices guidelines for the platform or service you're using. For example, on platforms like Vercel, Netlify, or Heroku, you can safely set environment variables through their control panels.

After setting these variables, all HTTP requests in your Nuxt.js application will automatically use the correct baseURL, whether in development or production environments.

2024年6月29日 12:07 回复

你的答案