首页 > 解决方案 > JavaScript/userscript:获取重定向到被 CORS 阻止的 url 的 GET 请求的重定向 url

问题描述

我正在为站点 a编写用户脚本。在站点 a上有一个指向不同路由的链接,该链接重定向到站点 b上的路由。只要我在站点 a登录,重定向就可以工作。我需要将重定向 URL(站点 b)发送到我的服务器。我需要从用户脚本中获取 url,以便重定向工作。

使用 $.ajax 通过 GET 请求点击链接,我在控制台中收到此错误:

Access to XMLHttpRequest at 'site b/route' (redirected from 'site a/link route') from origin 'site a' has been blocked by CORS policy...

我不需要站点 b上重定向的内容,我只需要 url。我试过这个:

$.ajax({
    url: 'site a/link route',
    type: 'GET',
    success: function(data){ 
        console.log(data); // this will not run due to CORS
    },
    error: function(data) {
        console.log(data); // this runs, but can i get the redirect url (site b)?
    }
});

是否可以获得重定向网址?是否可以使用 XMLHttpRequest 来做到这一点?

编辑:我几乎放弃了这个。我找到了另一个使用扩展的解决方案,并且与这个问题完全无关。如果这个问题得到新的答案/评论,我仍然会尝试找到一个有效的答案。

标签: javascriptjqueryxmlhttprequesttampermonkeyuserscripts

解决方案


您可以使用代理,

https://cors-anywhere.herokuapp.com/

在你的代码上,你可以做这样的事情,

$.ajax({
url: 'https://cors-anywhere.herokuapp.com/' + 'site a/link route',
type: 'GET',
success: function(data){ 
    console.log(data); // this will not run due to CORS
},
error: function(data) {
    console.log(data); // this runs, but can i get the redirect url (site b)?
}

});


推荐阅读