Vue项目中跨域的几种方式

经常使用vue + webpack搭建项目,但在请求某些json数据时存在跨域问题,此时有几种修改方法

1. 修改后台header, 但如果只是请求外部数据,是没法修改后台配置的

1 header('Access-Control-Allow-Origin:*');//允许所有来源访问 
2 header('Access-Control-Allow-Method:POST,GET');//允许访问的方式

2. 修改webpack配置 , 这是使用webpack选项devServer的代理功能 proxy

1 proxyTable: { 
2   '/api': { 
3     target: '填写请求源地址', //源地址 
4     changeOrigin: true, //是否跨域
5     pathRewrite: { 
6       '^/api': '' //路径重写 
7       } 
8   } 
9 }

注意:如果不设置pathRewrite则可能会出现以上报错

另外:proxyTable是在vue-cli2.0项目中config/index.js配置好的选项, 实际上它指向build/webpack.dev.config.js中的devServer.proxy

在新版的@vue/cli中(即vue-cli3.0)没有直接暴露出webpack的配置,只需在根目录下自行创建vue.config.js然后配置如下

 1 module.exports = {
 2     devServer: {
 3     proxy: {
 4         '/api': {
 5         target: '填写请求源地址',
 6         ws: true,
 7         changeOrigin: true,
 8                 pathRewrite: {
 9                    '^/api': ''
10                 }
11         }
12     }
13      }
14 }        

最后一般在组件中使用axios或者fetch请求本地服务即可,此时外部数据已经被转到了本地服务器中

1 axios.get('/api/xxx')
2   .then(res => {
3       console.log(res)
4   })
5   .catch(err => {
6       console.log(err)
7 })
 1 fetch('/api/xxx', {
 2   method: 'GET',
 3   headers: {
 4       'content-type': 'application/json'
 5   },
 6   mode: 'no-cors'
 7   })
 8   .then(res => res.json())
 9   .then(json => {
10       console.log(json)
11    })

3.使用jQuery的JSONP()

1 $.ajax({
2   url: '请求的源地址',
3   type: 'GET',
4   dataType: 'JSONP',
5   success(res) {
6      console.log(res)
7    }
8 })
原文地址:https://www.cnblogs.com/hughes5135/p/10183445.html