Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the interface error after vue project is packaged

2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

本篇内容介绍了"vue项目打包之后接口出现错误怎么解决"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

错误信息

这是新建一个项目还原问题,node简单写了个数据返回

关键代码const express = require('express')const app = express();// 解决跨域问题app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS'); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header('Access-Control-Allow-Headers', 'Content-Type'); next();})// 调用接口直接返回一个数组app.get('/getData', (req, res) => { res.send([ { id: 1, name: 'GAI' }, { id: 2, name: 'keyNg' }, { id: 3, name: '闪火' } ])})// api/index.jsimport axios from 'axios'export function getData() { return axios({ url: 'api/getData', method: 'get' })}// home.vuemounted() { getData().then(res => { console.log(res); })},打包前

打包后

解决方式设置环境变量

引用一句官网原话:

请注意,只有 NODE_ENV,BASE_URL 和以 VUE_APP_ 开头的变量将通过 webpack.DefinePlugin 静态地嵌入到客户端侧的代码中。这是为了避免意外公开机器上可能具有相同名称的私钥。

1.根目录新增.env.development文件(会在开发环境被载入)

// .env.developmentVUE_APP_TITLE = '温情dev'VUE_APP_ENV = 'dev'VUE_APP_BASE_URL = 'http://localhost:3000'

2.根目录新增.env.production文件(会在生产环境被载入)

// .env.productionVUE_APP_TITLE = '温情pro'VUE_APP_ENV = 'pro'VUE_APP_BASE_URL = 'http://localhost:3000'

3.改一下 axios 请求方法

// api/index// 这里只是简单解决一下问题// 重点就是把开发环境和生产环境请求地址区分开来就可以了, 根据实际情况自行改动import axios from 'axios'let baseURL = '';// process.env.VUE_APP_ENV拿到我们在前面设置的模式,// 如果现在是开发环境会使用`.env.development`里面设置的环境变量等于`dev`// 如果现在是生产环境会使用`.env.production`里面设置的环境变量等于`pro`if(process.env.VUE_APP_ENV === 'dev') { baseURL = '/api';} else { baseURL = process.env.VUE_APP_BASE_URL}export function getData() { return axios({ url: `${baseURL}/getData`, method: 'get' })}

小提示:

.env.development和.env.production文件修改之后记得重新跑一下项目

"vue项目打包之后接口出现错误怎么解决"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report