【Vue+Node】解决axois请求数据跨域问题

项目基于Vue前端+Node后台,启动两个服务,请求数据时,端口不一致造成跨域报错:

(No 'Access-Control-Allow-Origin' header is present on the requested resource)

【Vue+Node】解决axois请求数据跨域问题

经过查官方API得到以下两种思路:

1、在Node后台中设置,允许访问

   1.1、用代码控制

app.all('*', function(req, res, next) {  
  res.header("Access-Control-Allow-Origin", "http://localhost:8080");  
  res.header("Access-Control-Allow-Headers", "X-Requested-With");  
  res.header("Access-Control-Allow-Methods","POST,GET");  
  res.header("X-Powered-By",' 3.2.1')  
  res.header("Content-Type", "application/json;charset=utf-8");  
  next();  
});

   1.2、安装Core包,例如:

npm install cors --save
const cors = require('cors')
app.use(
  cors({
    origin: ['http://localhost:8080'], //前端地址
    methods: ['GET', 'POST'],
    alloweHeaders: ['Conten-Type', 'Authorization']
  })
)

 但,若之前遇到后台不是自己开发的接口,而是第三方接口,例如,Google,这样就无法从服务器设置入手。

 

2、在vue.config.js中进行代理配置:(proxy)

  proxy: { // 配置跨域
      '/api': {
        target: 'http://localhost:3001/',
        ws: true,
        changOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    },

  在页面调用的时候,用api代替 http://localhost:3001/

  axios.get('api/test/fscontent') //调用了http://localhost:3001/test/fscontent接口
    .then(response => {
      console.log(response.data)
    })