vue-resource - vue-source跨域请求被拒绝,后端相同设置,jQuery ajax可以请求

查看:149
本文介绍了vue-resource - vue-source跨域请求被拒绝,后端相同设置,jQuery ajax可以请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

1、vue-source跨域问题,已经在后端设置了response.setHeader("Access-Control-Allow-Origin", "*");使用jQury请求后端可以响应,但采用VueSource就报---Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.---
代码如下:《jQuery的和VueSource的都在下面》

userSignin:function({commit}, user){

/* var loginFlag=false; //false

        $.ajax({
            type:"post",
            url:"http://localhost:80/StockAnalyse/LoginServlet",
            data:"flag=ajaxlogin&loginName="+user.name+"&loginPwd="+user.id,
            async:false, //这里没有用promise,须设置为同步,
            dataType:"json",
            success:function(data){
              loginFlag=true;
            },
            erro:function(){
              console.log("something wrong");
            }
         });    
          if(loginFlag){
           commit("userSignin", user);  
         }    */               
     Vue.http({
      method:"post",
      url:"http://localhost:80/StockAnalyse/LoginServlet",
      data:{"flag":"ajaxlogin","loginName":user.name,"loginPwd":user.id}, 
      //data:
      headers: {"X-Requested-With": "XMLHttpRequest"},  
      credientials:false, 
      emulateHTTP: true     
    }).then(function(response){
      console.log("it's done"+response.string());
      commit("userSignin", user);  

其实就开发时涉及到跨域,后面会把前端直接扔到后端服务器项目包里,就不存在跨域的问题了, 求大神写支支招,Vue的文档https://github.com/pagekit/vu...提供的内容确实有限

               
    },function(response){
      console.log("game over");
    });

解决方案

其实和选择什么方式无关,既然服务器端允许跨域,那采用这个方式应该是可以的,后面结合jquery默认配置看,配置VUE-RESOURCE时缺少传输的网络文件类型缺少配置,headers: Content-Type不设置,默认值为json/application,在cors定义中,如果Content-Type值不为application/x-www-form-urlencoded,
multipart/form-data或text/plain,都被视为非简单请求,即预检请求。所以会报Response to preflight request doesn't pass access control check

      Vue.http({
      method:"post",
      url:"http://localhost:80/StockAnalyse/LoginServlet",       
      params:{"flag":"ajaxlogin","loginName":user.name,"loginPwd":user.id}, 
      headers: {"X-Requested-With": "XMLHttpRequest"},
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}, //新增加
      credientials:false, 
      emulateJSON: true     
    }).then(function(response){
      console.log(response.data);
      commit("userSignin", user); 
      return true;
    },function(response){
      console.log("game over");
      return false;
    }); 

这篇关于vue-resource - vue-source跨域请求被拒绝,后端相同设置,jQuery ajax可以请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆