关于跨域请求数据的问题

vue-resource 跨域请求

1、客户端:

  (1)在webpack.config.js(config—>index.js)文件里设置代理(可以同时设置多个)

dev: {
    env: require('./dev.env'),
    port: 8080,  //设置访问的端口号
    autoOpenBrowser: true, //自动打开浏览器
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
        '/api': {
            target: 'http://localhost:8888', //设置调用接口域名和端口号别忘了加http
            changeOrigin: true,
            pathRewrite: {
                '^/api': '/' //这里理解成用‘/api’代替target里面的地址,组件中我们调接口时直接用/api代替
                    // 比如我要调用'http://0.0:300/user/add',直接写‘/api/user/add’即可 代理后地址栏显示/
            }
        }
    }
  ...

  (2)在组件中编辑(下面是POST方法,GET方法也一样)

this.$http.post("http://localhost:8888/login?user=blue&pass=123456")
      .then(function(response) {
        console.log("成功");      
        console.log(response.body);
      }, function(response) {
        console.log("失败");
        console.table(response);
      });

//或者使用axios(记得安装和引入axios模块)
import axios from "axios"
axios.get("api/login?user=blue&pass=123456")
      .then(function(response) {
        console.log("成功");      
        console.log(response.data);
      }, function(response) {
        console.log("失败");
        console.table(response);
      });

2、服务端:

  nodeJS 用express作为服务端

server.use('/login', function (req, res){
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
   ...
原文地址:https://www.cnblogs.com/lianchenxi/p/9668663.html