简体   繁体   中英

How to dynamically set api url paths in Vue?

Edit (2): I'll just hard code in the url for now. Still seeking solutions to dynamic assigning it though!

Edit: I've tried what I was suggested by Soni. However, it is still not working (I get a 404 error).

My.env file now (this is present in both the root directory of my project, and the directory of my front end, it's local because I'm trying to test the concept):

NODE_ENV=development
PORT=8081
VUE_APP_API_BASE_URL=http://localhost:8081/api

My code:

const API_URL = `${process.env.VUE_APP_API_BASE_URL}/auth`;

The below text is old. (I will not edit it.)

The title says it all, more or less. I'm using @vue/cli 5.0.8 and having some trouble with figuring it out. I either get a 404, or a blank screen.

Here's a code snippet if it helps.

import axios from 'axios';

const API_URL = 'http://localhost:8081/api/auth/';

class AuthService {
  login(user) {
    return axios
      .post(API_URL + 'signin', {
        username: user.username,
        password: user.password
      })
      .then(response => {
        if (response.data.accessToken) {
          localStorage.setItem('user', JSON.stringify(response.data));
        }
        return response.data;
      });
  }
}

Locally, it's

const API_URL = 'http://localhost:8081/api/test/'

I've attempted

const API_URL = process.env.ROOT_API/test;

But no dice. I haven't fiddled with making a .env.production file because, far as I know as a novice, the .env file isn't meant to be pushed up onto Github, and I plan to deploy this on Heroku, which offers its own .env file. The ROOT_API comes from a file I tossed out after it didn't work. The said file is below.

dev.env.js

'use strict'
const merge = require('webpack-merge')
const prodEnv = require ('./prod.env')

module.exports = merge(prodEnv, {
    NODE_ENV: '"development"',
    ROOT_API: '"http://localhost/api"'

// There was a prod.env.js too, but I won't bother to post it. 
})

Appreciate any aid.

According to the doc , a good way is to create files as per environments, like-

build.env.local (for the local environment)
build.env.test (for test environment)
build.env.production (for production environment)

And the different endpoints as per the environments can be set like this-

// build.env.local
VUE_APP_ROOT_API="http://localhost:8081/api/auth/"

// build.env.test
VUE_APP_ROOT_API="https://<test-domain>/api/auth/"

// build.env.production
VUE_APP_ROOT_API="https://<production-domain>/api/auth/"

And to use those env variables anywhere, use them like this-

var root_api = process.env.VUE_APP_ROOT_API

You can use the same way if you deploy the app to Heroku. Here is the complete guide on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM