zoukankan      html  css  js  c++  java
  • 【Vue+Node】解决axois请求数据跨域问题

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

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

    经过查官方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)
        })
    

      

  • 相关阅读:
    LCA模板
    bzoj1660:[Usaco2006 Nov]badhair乱头发节
    不老的传说
    田忌赛马
    最短路径问题
    hdu2421-Deciphering Password-(欧拉筛+唯一分解定理+积性函数+立方求和公式)
    hdu1215-七夕节-(埃氏筛+唯一分解定理)
    迷宫-(bfs)
    区间或和-(位运算)
    海啸-(矩阵前缀和)
  • 原文地址:https://www.cnblogs.com/alwaysblog/p/10535530.html
Copyright © 2011-2022 走看看