跨域问题webpack的代理
Posted web交流
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了跨域问题webpack的代理相关的知识,希望对你有一定的参考价值。
在前后端分离的年代前端经常会遇到跨域的问题,后端解决还好说,如果后端不愿已的话就得自己去操作了。
我们得在项目中找到webpack的config配置文件让后打开index.js
在index.js里面找到proxyTable这个配置,这个就是webpack专们为我们解决跨域准备的。
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api':{
target:'http://api.douban.com/v2',//豆瓣的代理
changeOrigin:true,
pathRewrite:{
'^/api':''
}
}
},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
/**
* Source Maps
*/
productionSourceMap: false,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: true,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}
在main.js里面
vue.prototype.Host = '/api'
在页面上用
console.log(this.Host,'代理')
this.$Aiox.get(this.Host+'/movie/top250',{
params:{
count:10,
start:0
}
}).then(res=>{
console.log(res)
}).catch(error=>{
console.log(error)
})
打印
成功完成
其实跨域的问题不怎么多,好好更后台跟后台沟通下也就基本解决了。也就没前端什么事情了
axios的全局配置
统一设置路径
axios.defaults.baseURL = 'url';
统一设置token
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN
这个不用说啦
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
以上是关于跨域问题webpack的代理的主要内容,如果未能解决你的问题,请参考以下文章