vue-cli node express本地开发,出现跨域问题怎么解决?

这几天使用vue-cli 2.x版本创建一个简单项目,使用axios请求数据,node express搭建的简单后台,但是遇到跨域问题实在让我头痛。看了很多的博客仍旧为解决,再此寻求答案。谢谢了

1、在node中的代码,启动node服务器成功,能请求到数据。但解决跨域我找了很多个都无济于事

//全局允许跨域
app.all("*",(req, res, next) => {
  res.header('Access-Control-Allow-Credentials','true');
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  next();
})
// app.all('*', function (req, res, next) {
//   res.header("Access-Control-Allow-Origin", "");
//   res.header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild");
//   res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
//   res.header("X-Powered-By",  "3.2.1")
//   res.header("Content-Type", "application/json;charset=utf-8");
//   next();
// })
// // 自定义跨域中间件
// var allowCors = function(req, res, next) {
//   res.header('Access-Control-Allow-Origin', req.headers.origin);
//   res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
//   res.header('Access-Control-Allow-Headers', 'Content-Type');
//   res.header('Access-Control-Allow-Credentials','true');
//   next();
// };
// app.use(allowCors);//使用跨域中间件

2、在vue中

// main.js全局 axios
import Axios from 'axios'
Vue.prototype.$ajax = Axios
btn(){
        this.$ajax.get('http://localhost:3000/test')
        .then(res=>{
          console.log(res)
        })
        .catch(err=>{
          console.log(err)
        })
      }

报错1.png

我想,后端要是开启了允许跨域,前端就不需要代理了,我打开了浏览器跨域插件,还是一样的。于是我就改xue-cli中的配置文件:config/index.js

proxyTable: {
      '/api': {  //代理地址  
          target: 'http://localhost:3000/',  //需要代理的地址  
          changeOrigin: true,  //是否跨域  
          secure: false,      //是否启用https
          pathRewrite: {  
              '^/api': ''  
          }
      }
    },

更改请求URL:

btn(){
        this.$ajax.get('/api/test')
        .then(res=>{
          console.log(res)
        })
        .catch(err=>{
          console.log(err)
        })
      }

但结果却给我这个:2.png
看着像是不走代理,我很纳闷,我以前使用这样的代理就没事,为什么现在有事了呢?

老哥们 你们遇到吗?我无解了………………

阅读 3.2k
1 个回答

**我被坑惨了,其实这个只要清除浏览器缓存就行,我怎么去说啊~~~~~~~~~~~~~~~~~~~~~~~~~~~~
欲哭无泪~~~~~~~~~~~~~~~~**

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题