Vue代理報(bào)錯(cuò)404問(wèn)題及解決(vue配置proxy)
Vue代理報(bào)錯(cuò)404問(wèn)題
問(wèn)題描述:

代理后出現(xiàn)404:

第一種路徑拼接 /api 情況
const path = require('path');
function resolve(dir) {
return path.resolve(__dirname, dir)
}
module.exports = {
publicPath: process.env.NODE_ENV === "production" ? "./" : "/",
assetsDir: "assets",
configureWebpack: {
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'@': resolve('src'),
'assets': resolve('src/assets'),
'css': resolve('src/assets/css'),
'images': resolve('src/assets/images'),
'views': resolve('src/views'),
'components': resolve('src/components'),
'api': resolve('src/api'),
'mixins': resolve('src/mixins'),
'store': resolve('src/store'),
'service': resolve('src/service'),
}
}
},
devServer: {
port: 8081,
hot: true,
// open: 'Chrome',
proxy: {
// change xxx-api/login => mock/login
// detail: https://cli.vuejs.org/config/#devserver-proxy
'/api': {
target: 'https://www.xxxxxx.com/',
changeOrigin: true,
secure: true,
pathRewrite: {
'^/api': '/'
}
},
},
},
css: {
loaderOptions: {
css: {},
postcss: {
plugins: [
require('postcss-px2rem')({
remUnit: 192
})
]
}
}
},
productionSourceMap: false,
};

使用如下:

結(jié)果如下:

缺點(diǎn) :打包后的請(qǐng)求路徑會(huì)多個(gè) /api
第二種路徑不變情況

這種寫(xiě)法也可以:

注意:這時(shí)候就按原來(lái)的路徑就可以了;

結(jié)果如下:

缺點(diǎn):配置多個(gè)代理要注意代理的先后順序;
注意點(diǎn)
代理的順序:從前往后匹配的,先匹配到哪個(gè)就用哪個(gè);
新增說(shuō)明:配置多個(gè)代理怎么搞?
配置多個(gè)代理怎么搞?
'use strict'
const path = require('path')
// const SkeletonWebpackPlugin = require('vue-skeleton-webpack-plugin')
const defaultSettings = require('./src/settings.js')
function resolve(dir) {
return path.join(__dirname, dir)
}
const name = defaultSettings.title || 'xxx' // page title
// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following methods:
// port = 9527 npm run dev OR npm run dev --port = 9527
const port = process.env.port || process.env.npm_config_port || 9527 // dev port
// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
/**
* You will need to set publicPath if you plan to deploy your site under a sub path,
* for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
* then publicPath should be set to "/bar/".
* In most cases please use '/' !!!
* Detail: https://cli.vuejs.org/config/#publicpath
*/
// publicPath: process.env.ENV === 'production' ? '/' : '/',
publicPath: process.env.ENV === 'production' ? '/' : '/',
outputDir: 'dist',
assetsDir: 'static',
lintOnSave: process.env.NODE_ENV === 'development',
productionSourceMap: false,
devServer: {
host: 'localhost',//target host
port: port,
overlay: {
warnings: false,
errors: true
},
proxy: {
[process.env.VUE_APP_BASE_BRAND_API]: {
target: 'http://10.44.62.64:8090',
changeOrigin: true,
pathRewrite: {
['^' + process.env.VUE_APP_BASE_BRAND_API]: ''
}
},
// change xxx-api/login => mock/login
// detail: https://cli.vuejs.org/config/#devserver-proxy
[process.env.VUE_APP_BASE_API]: {
// target: 'http://localhost:3100',
target: 'http://xx.xxx.xx.x:3100',
// target: `http://127.0.0.1:${port}/mock`,
changeOrigin: true,
pathRewrite: {
['^' + process.env.VUE_APP_BASE_API]: ''
}
},
},
// proxy:{
// // 當(dāng)你請(qǐng)求是以/api開(kāi)頭的時(shí)候,則我?guī)湍愦碓L問(wèn)到http://localhost:3000
// // 例如:
// // /api/users http://localhost:3000/api/users
// // 我們真是服務(wù)器接口是沒(méi)有/api的
// "":{
// target:"http://localhost:31009",
// changeOrigin: true,// 如果接口跨域,需要進(jìn)行這個(gè)參數(shù)配置
// pathRewrite:{"^":""}
// }
// }
// after: require('./mock/mock-server.js')
},
configureWebpack: {
// provide the app's title in webpack's name field, so that
// it can be accessed in index.html to inject the correct title.
name: name,
resolve: {
alias: {
'@': resolve('src')
}
}
},
// css: {
// extract: true // 是否使用css分離插件 ExtractTextPlugin(開(kāi)啟骨架屏必須這個(gè)配置)
// },
chainWebpack(config) {
config.plugin('html').tap(args => {
// 添加初始化變量
args[0].monitorId = process.env.VUE_APP_MONITOR_ID
return args
})
config.plugins.delete('preload') // TODO: need test
config.plugins.delete('prefetch') // TODO: need test
// set svg-sprite-loader
config.module
.rule('svg')
.exclude.add(resolve('src/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
// set preserveWhitespace
config.module
.rule('vue')
.use('vue-loader')
.loader('vue-loader')
.tap(options => {
options.compilerOptions.preserveWhitespace = true
return options
})
.end()
config
// https://webpack.js.org/configuration/devtool/#development
.when(process.env.NODE_ENV === 'development',
config => config.devtool('cheap-source-map')
)
config
.when(process.env.NODE_ENV !== 'development',
config => {
config
.plugin('ScriptExtHtmlWebpackPlugin')
.after('html')
.use('script-ext-html-webpack-plugin', [{
// `runtime` must same as runtimeChunk name. default is `runtime`
inline: /runtime\..*\.js$/
}])
.end()
config
.optimization.splitChunks({
chunks: 'all',
cacheGroups: {
libs: {
name: 'chunk-libs',
test: /[\\/]node_modules[\\/]/,
priority: 10,
chunks: 'initial' // only package third parties that are initially dependent
},
elementUI: {
name: 'chunk-elementUI', // split elementUI into a single package
priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
},
commons: {
name: 'chunk-commons',
test: resolve('src/components'), // can customize your rules
minChunks: 3, // minimum common number
priority: 5,
reuseExistingChunk: true
}
}
})
config.optimization.runtimeChunk('single')
}
)
// 骨架屏配置
// config
// .plugin('SkeletonWebpackPlugin')
// .use(new SkeletonWebpackPlugin({
// webpackConfig: {
// entry: {
// app: resolve('src/skeleton.js'),
// }
// },
// minimize: true,
// quiet: true,
// router: {
// mode: 'history',
// routes: [{
// path: '*',
// skeletonId: 'common-skeleton'
// }]
// }
// }))
}
}
注意.env.development中的配置
NODE_ENV = 'development' # just a flag ENV = 'development' # base api(當(dāng)使用mock.js時(shí),切換dev-api) # VUE_APP_BASE_API = '/dev-api' VUE_APP_BASE_API = '' # vue-cli uses the VUE_CLI_BABEL_TRANSPILE_MODULES environment variable, # to control whether the babel-plugin-dynamic-import-node plugin is enabled. # It only does one thing by converting all import() to require(). # This configuration can significantly increase the speed of hot updates, # when you have a large number of pages. # Detail: https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/babel-preset-app/index.js VUE_CLI_BABEL_TRANSPILE_MODULES = true # 圖片和附件上傳文件夾 VUE_APP_OSS_FOLDER='test/xxx/' # 品牌項(xiàng)目 (這里為了代理,要多加個(gè) /brand,當(dāng)然可以自己定義) VUE_APP_BASE_BRAND_API = '/brand'
配置了 .env.development 中的代理路徑后,這樣api接口js文件中就不用多寫(xiě)個(gè) /brand,不用寫(xiě)成 /brand/saveOrUpdate ,請(qǐng)求路徑也會(huì)存在 /brand ,baseURL拼接的原因,這樣打包也并不影響,畢竟打包的是生產(chǎn)環(huán)境的路徑;



總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue自定義詢(xún)問(wèn)彈框和輸入彈框的示例代碼
這篇文章主要介紹了Vue自定義詢(xún)問(wèn)彈框和輸入彈框,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-06-06
Vue異步更新機(jī)制及$nextTick原理的深入講解
最近在學(xué)習(xí)一些底層方面的知識(shí),所以想做個(gè)系列嘗試去聊聊這些比較復(fù)雜又很重要的知識(shí)點(diǎn),下面這篇文章主要給大家介紹了關(guān)于Vue異步更新機(jī)制及$nextTick原理的相關(guān)資料,需要的朋友可以參考下2022-04-04
vue keep-alive實(shí)現(xiàn)多組件嵌套中個(gè)別組件存活不銷(xiāo)毀的操作
這篇文章主要介紹了vue keep-alive實(shí)現(xiàn)多組件嵌套中個(gè)別組件存活不銷(xiāo)毀的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-10-10
vue監(jiān)聽(tīng)滾動(dòng)條頁(yè)面滾動(dòng)動(dòng)畫(huà)示例代碼
Vue是一套用于構(gòu)建用戶(hù)界面的漸進(jìn)式框架,與其它大型框架不同的是,Vue?被設(shè)計(jì)為可以自底向上逐層應(yīng)用,下面這篇文章主要給大家介紹了關(guān)于vue監(jiān)聽(tīng)滾動(dòng)條頁(yè)面滾動(dòng)動(dòng)畫(huà)的相關(guān)資料,需要的朋友可以參考下2023-06-06
vue中利用three.js實(shí)現(xiàn)全景圖的完整示例
這篇文章主要給大家介紹了關(guān)于vue中利用three.js實(shí)現(xiàn)全景圖的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
vue輕松實(shí)現(xiàn)虛擬滾動(dòng)的示例代碼
移動(dòng)端網(wǎng)頁(yè)的日常開(kāi)發(fā)中,偶爾會(huì)包含一些渲染長(zhǎng)列表的場(chǎng)景,本文主要介紹了vue 虛擬滾動(dòng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-07-07

