【问题标题】:Get URL after redirect重定向后获取网址
【发布时间】:2020-10-08 10:25:19
【问题描述】:

我正在构建一个 React 应用程序,我在其中通过 fetch 发送一个 API。为了获得正确的 API 响应,我需要发送一个特定的链接,但用户可能能够以另一种格式提供这些链接,如果在浏览器中打开这些链接会重定向到正确的格式。

例子:

此链接https://soundcloud.app.goo.gl/u6XXuqp3Q7Q7WXgH8
重定向到:https://soundcloud.com/gary-j/ladies-on-mars-kiss-me-baby?p=i&c=0
如果在浏览器中打开。

在 Javascript 中有没有办法从第一个链接中获取第二个链接?

谢谢!

//编辑: 我都在尝试使用 fetch 和 request。使用请求方式如下:

import React, {Component} from 'react';
const request = require('request');

class Getlink extends Component {
getRequest = () => {
    request('https://soundcloud.app.goo.gl/u6XXuqp3Q7Q7WXgH8', function (error, response, body) {
    console.error('error:', error); 
    console.log('statusCode:', response && response.statusCode); 
    console.log('body:', body);
});
}

render() {
return (
    {this.getRequest()}
)}
}

出现以下错误

Access to fetch at 'https://soundcloud.app.goo.gl/u6XXuqp3Q7Q7WXgH8' from 
origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-
Control-Allow-Origin' header is present on the requested resource. If an 
opaque response serves your needs, set the request's mode to 'no-cors' to 
fetch the resource with CORS disabled.

加上一个 GET 失败的错误。

这是我从本地做的正常反应吗?

【问题讨论】:

  • 如果您查询第一个 url,您将收到的第一个响应是包含第二个 url 的重定向响应
  • 谢谢!请检查我的编辑!

标签: javascript reactjs url redirect


【解决方案1】:

重定向网址在response.headers.location。对于任何重定向响应代码,您都可以使用 headers.location 递归获取 url。

例如,对curl 的响应显示响应代码为302 (Found),并且重定向网址在location 标头中指定。

curl -s -o /dev/null -D -  https://soundcloud.app.goo.gl/u6XXuqp3Q7Q7WXgH8 
HTTP/2 302 
content-type: application/binary
vary: Sec-Fetch-Dest, Sec-Fetch-Mode, Sec-Fetch-Site
cache-control: no-cache, no-store, max-age=0, must-revalidate
pragma: no-cache
expires: Mon, 01 Jan 1990 00:00:00 GMT
date: Thu, 08 Oct 2020 10:47:50 GMT
location: https://soundcloud.com/gary-j/ladies-on-mars-kiss-me-baby?ref=clipboard&p=i&c=0
content-security-policy: script-src 'nonce-pxqEOSDMS5AkBDmVHzvHUQ' 'unsafe-inline';object-src 'none';base-uri 'self';report-uri /_/DurableDeepLinkUi/cspreport;worker-src 'self'
server: ESF
content-length: 0
x-xss-protection: 0
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
alt-svc: h3-Q050=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-27=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-T050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"

【讨论】:

  • 谢谢!我编辑了我的问题,因为它不适合我?
【解决方案2】:

我想出了一些东西,我猜这个问题与网站有关。我发现使用 cors-anywhere 确实有助于提出请求,但会返回 403 Forbidden。您可以在这里尝试:https://robwu.nl/cors-anywhere.html 并输入我要解析的网址。

fetch("https://cors-anywhere.herokuapp.com/https://soundcloud.app.goo.gl/u6XXuqp3Q7Q7WXgH8")
        .then((result) => {
        console.log(result)
    })

【讨论】:

    猜你喜欢
    • 2013-03-09
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 2013-02-16
    相关资源
    最近更新 更多