如何在 vue.config.js 中设置 API 路径用于生产?

How to set API path in vue.config.js for production?

我正在使用 vue cli3 进行设置。我已经在 vue.config.js 文件中设置了 devServer api:

devServer: {
    proxy: {
        '/api': {
            target: 'http://localhost:1888/apps/test/mainapp.php/',
            changeOrigin: true,
        },
    },
}

我还需要设置路径 'https://server/myapp/main.php/' as the production API path, but I can't seem to find any info in the documentation 如何设置。感谢任何帮助。

我在代码中所做的简要示例:

methods: {
    login() {
        this.axios.post('/api/test')
            .then((resp) => {
                console.log(resp);
            })
            .catch(() => {
                console.log('err:' , err);
            });
    },
},

当您执行 yarn/npm run build 时,您的 devServer 不会 运行。您只获得了要提供的转译后的 javascript。您需要在 .env 文件中更改 URL。

发展:

.env

VUE_APP_API_ENDPOINT = '/api'

生产:

.env.production

VUE_APP_API_ENDPOINT ='https://server/myapp/main.php'

那么你的 XHR 请求库应该在发出请求时使用这些环境变量,比如使用 axios:

axios[method](process.env.VUE_APP_API_ENDPOINT, data)

其中 method 将是 GET/POST/PUT/DELETE

请注意,您将受到跨源资源共享制定的规则的限制。如果您的服务器不允许 URL 为您的 Vue.js 页面提供服务,您需要打开它。

您不需要对您的 devServer 配置进行任何更改,因为您的 .env 现在将声明发送到 /api 的 xhr 请求,它仍然会为您代理。

您在代码中使用了 axios,因此您可以尝试:

// service.js
import axios from 'axios';
axios.defaults.baseURL = 'https://server/myapp/main.php/';
export default axios;

// main.js
Vue.prototype.$axios = axios;

// In your component
login() {
    this.$axios.post('/api/test', data)
        .then((resp) => {
            console.log(resp);
        })
        .catch(() => {
            console.log('err:' , err);
        });
}

然后每个请求都将使用您设置的默认 baseUrl 发送。

查看 axios

的更多选项

如果你的vue-cli版本高于3.x,那么添加你的

development variables in .env file

production variables in .env.production file

只有以 VUE_APP_ 开头的变量才会静态嵌入到带有 webpack.DefinePlugin 的客户端包中。您可以在您的应用程序代码中访问它们:console.log(process.env.VUE_APP_SECRET) Vue Doc