vue配合java 等前后端分离实现微信授权

 //scope为info时显示用户授权页面
    @RequestMapping("")
    public void loginAuth(HttpServletResponse httpServletResponse){

        try {
            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                    "appid=" +appId+
                    "&redirect_uri="+URLEncoder.encode(backUrl,"utf-8")+
                    "&response_type=" + response_type +
                    "&scope=" + scope +
                    "&state=STATE#wechat_redirect";
            httpServletResponse.sendRedirect(url);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

第一个redirect_uri就是下面这个接口的地址

//通过回调地址获取code
    @RequestMapping("callBack")
    public void callBackServer(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse){

        //在request中获取code
        String code = httpServletRequest.getParameter("code");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + appId+
                "&secret=" + appsecret +
                "&code=" + code +
                "&grant_type=" + grant_type;

        try {
            JSONObject jsonObject = AuthUtil.getUrl(url);

            //获取openId
            String openid = jsonObject.getString("openid");
            //获取access_token
            String access_token = jsonObject.getString("access_token");

            //获取用户信息
            String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?" +
                    "access_token=" + access_token +
                    "&openid=OPENID" + openid +
                    "&lang=zh_CN";
            JSONObject userInfo = AuthUtil.getUrl(userInfoUrl);
            System.out.println(userInfo);

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

如上2段是按照微信的规则去调用的,第一段我不知道为啥要重定向,但是直接访问就是获取不到结果集,第二段是第一段回调后执行的方法,能获取openId这个是关键。。

但现在的问题就是我用vue请求后端接口(第一个)时会报跨域问题,我在index.js设置了解决跨域的问题,但是问题来了,在后台重定向访问微信接口,又出跨域的异常了。。怎么解决,求大神帮帮小弟

这是vue配置跨域的地方
地址是用类似花生壳的一个工具映射的

    proxyTable: {
      '/user': {
        target: 'http://wangzz.free.idcfengye.com/login', // 你请求的第三方接口
        changeOrigin: true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
        pathRewrite: {  // 路径重写,
          '^/login': ''  // 替换target中的请求地址,也就是说以后你在请求http://api.douban.com/v2/XXXXX这个地址的时候直接写成/api即可。
        }
      }
    },

第一个接口是在微信上直接访问,看scope设置,可以是授权后跳转或者直接隐性跳转,但是都是必须在微信访问才会有效,不然会提示使用微信访问。

对于这个问题建议你直接在vue上做第一个接口跳转,而不是像传统获取接口访问来访问。

微信授权访问的域名需要与设置的白名单的域名一致,你本地做一下host指向