webpack处理跨域问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了webpack处理跨域问题相关的知识,希望对你有一定的参考价值。

参考技术A 1.百度搜索webpack

2.点击配置

3.找到proxy

4.devserve.proxy

5.复制粘贴到vue.config.js文件里面,最后一项去掉,target写接口地址

跨域问题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
port8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowserfalse,
errorOverlaytrue,
notifyOnErrorstrue,
pollfalse, // 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
cacheBustingtrue,
cssSourceMaptrue
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory'static',
assetsPublicPath'/',
/**
* Source Maps
*/
productionSourceMapfalse,
// 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
productionGziptrue,
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
bundleAnalyzerReportprocess.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处理跨域问题的主要内容,如果未能解决你的问题,请参考以下文章

跨域 webpack + vue-cil 中 proxyTable 处理跨域

webpack http-proxy-middleware 处理跨域 cookie

vue-webpack项目本地开发环境设置代理解决跨域问题

Webpack 配置 proxy 代理解决跨域问题

用webpack-dev-server开发时代理,决解开发时跨域问题

webpack跨域问题