简体   繁体   English

JavaScript ping URL并获取重定向的URL

[英]JavaScript ping a URL and get the redirected URL

In our AngularJS app I have an image URL like: 在我们的AngularJS应用中,我有一个图片网址,例如:

http://example.com/images/get/785746378

The issue is this redirects me to another URL which blocked: 问题是这将我重定向到另一个被阻止的URL:

http://another-example.com/images/f/gs/s/your-image.jpg

So the image is not working, but if I replace the domain so it's: 因此,该图像无法正常工作,但是如果我替换了域,则为:

http://example.com/images/f/gs/s/your-image.jpg

It works fine. 工作正常。

So I want to be able to ping the URL in JavaScript and find out what the redirected URL is and change the domain so it works before adding it to my img src 因此,我希望能够在JavaScript中对URL进行ping操作,找出重定向的URL是什么并更改域,以便在将其添加到img src之前可以正常工作

This should work fine: 这应该工作正常:

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);

Its not clear from your post how you are requesting the image. 从您的帖子中还不清楚您是如何请求图像的。 Assuming that you are requesting it using AJAX / $HTTP: 假设您使用AJAX / $ HTTP进行请求:

You can send HEAD request for original URL. 您可以发送HEAD请求以获取原始URL。 If HTTP HEAD requests are allowed on the server, you will get the HTTP 302 response with new location in the response header. 如果服务器上允许HTTP HEAD请求,您将在响应头中获得带有新location的HTTP 302响应。 You can do the required manipulation on this location and send GET request for the new URL of the image. 您可以在此location执行所需的操作,然后发送GET请求以GET图像的新URL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM