vue开发时,跨域问题解决方法

vue

问题:vue开发时,跨域问题解决方法

解决:做个代理转发即可

具体步骤:

1.vue环境 config下index.js文件  如下标红的设置转发代码

/api:,每个前端访问,自动加上/api

target:用来转发,后端访问地址,端口。

pathRewrite: 重写了访问url,即前端访问url中带/api/xxx,请求到后端,自动把这个/api去掉,否则后端访问不到。

// see http://vuejs-templates.github.io/webpack for documentation.

var path = require('path')

module.exports = {

build: {

env: require('./prod.env'),

index: path.resolve(__dirname, '../dist/index.html'),

assetsRoot: path.resolve(__dirname, '../dist'),

assetsSubDirectory: 'static',

assetsPublicPath: '/',

productionSourceMap: true,

// 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: false,

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

},

dev: {

env: require('./dev.env'),

port: 8080,

autoOpenBrowser: true,

assetsSubDirectory: 'static',

assetsPublicPath: '/',

proxyTable: {

'/api': {

target: 'http://127.0.0.1:5000/', //目标接口域名

changeOrigin: true, //是否跨域

pathRewrite: {

'^/api': '' //重写接口

}

}

},

// CSS Sourcemaps off by default because relative paths are "buggy"

// with this option, according to the CSS-Loader README

// (https://github.com/webpack/css-loader#sourcemaps)

// In our experience, they generally work as expected,

// just be aware of this issue when enabling this option.

cssSourceMap: false

},

configureWebpack: {

}

}

以上设置好之后,npm run dev启动时,自动会启动这个转发代理。很好的解决了跨域问题。

以上是 vue开发时,跨域问题解决方法 的全部内容, 来源链接: utcz.com/z/380208.html

回到顶部