[英]JavaScript ping a URL and get the redirected URL
在我们的AngularJS应用中,我有一个图片网址,例如:
http://example.com/images/get/785746378
问题是这将我重定向到另一个被阻止的URL:
http://another-example.com/images/f/gs/s/your-image.jpg
因此,该图像无法正常工作,但是如果我替换了域,则为:
http://example.com/images/f/gs/s/your-image.jpg
工作正常。
因此,我希望能够在JavaScript中对URL进行ping操作,找出重定向的URL是什么并更改域,以便在将其添加到img src
之前可以正常工作
这应该工作正常:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(response) {
var xhr = response.target;
if (xhr.readyState === 4 && xhr.status === 302) {
var redirectURL = xhr.location;
var imageURL = redirectURL.replace('http://another-example','http://example');
// change your image src here by imageURL
}
}
xhr.open('GET', 'http://example.com/images/get/785746378', true);
xhr.send(null);
从您的帖子中还不清楚您是如何请求图像的。 假设您使用AJAX / $ HTTP进行请求:
您可以发送HEAD
请求以获取原始URL。 如果服务器上允许HTTP HEAD
请求,您将在响应头中获得带有新location
的HTTP 302响应。 您可以在此location
执行所需的操作,然后发送GET
请求以GET
图像的新URL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.