最近几天我个人写音乐项目时遇到一个小问题,因为需要使用第三方接口的原因,可能会造成 请求跨域 的问题

如示:

Access to XMLHttpRequest at 'https://haser.top/' from origin 'http://localhost:63343' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

]这个问题可是耽误了我一段时间啊!!终于后来使用Java的Servlet来解决的

大概解决思路:
使用Java的servlet来帮我访问,访问之前加一些响应头,让对方服务器端认为这是个人在访问

方法代码:

 /**
     * 地址
     * @param postUrl
     */
    public static String GetUrl(String postUrl){
        Document doc = null;
        try {
            doc = Jsoup.connect(postUrl)
                    .header("Cookie", "__stripe_mid=06986f53-e033-4b1b-8d66-a293c203fa3e; _gcl_au=1.1.1964887636.1583134501; _ga=GA1.2.1122723002.1583134501; _gid=GA1.2.401037423.1583134501; __gads=ID=2d22c788acb05249:T=1583138393:S=ALNI_MbNYbfEpm4Fmb8SPRxoNwCmZxu_Dg; G_ENABLED_IDPS=google")
                    .header("accept","application/json, text/plain, */*")
                    .header("accept-encoding","gzip, deflate, br")
                    .header("accept-language","zh-CN,zh;q=0.9")
                    .header("authorization","0BCmojA2RIMfOo9t3lZDDSklv7sMN8V")
                    .header("content-type","application/json;charset=UTF-8")
                    .header("referer","https://haser.top/")
                    .header("sec-fetch-dest","empty")
                    .header("sec-fetch-mode","cors")
                    .header("sec-fetch-site","same-site")
                    .header("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36")
                    .timeout(60000)
                    .ignoreContentType(true)
                    .post();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(doc);
        return  doc.toString();


    }

Servlet代码:

if (req.getParameter("url")!=null){
    String url = req.getParameter("url");
    String str = GetUrl(url);   
     str = Methods.delHtmlTags(str);
     Object json = JSON.toJSON(str);//转为json格式
     response.setContentType("text/json;charset=utf-8");//浏览器响应为json
     PrintWriter writer = response.getWriter();
     writer.println(json);//输出
}

js代码:(Servlet路径?url=之前跨域的地址)

到最后这个问题就完美解决了

PS:源码因为某些原因就不放出来了,有需要的可以联系我
扫描二维码,在手机上阅读!
Last modification:June 16th, 2021 at 10:37 am
请我喝一瓶农夫山泉嘛?