如何在 JavaScript 中获得没有端点的响应?

How to get a response without a endpoint in JavaScript?

这是我写的代码:

...
    await fetch('https://google.com', {
      method: "GET",
      mode: "no-cors"
    })
    .then((response) => {
      console.log(response.body);
      console.log(response.status);
      return response.text();
    })
    .then((responseText) => {
      console.log(responseText);
    })
    .catch((error) => {
      console.log(error.toString());
    });
...

https://google.com (O)
https://google.com/test (X)

我想从没有端点的 URL 获得响应 (HTML)。所以我使用 Fetch API 发送了 HTTP 请求,但它继续 return 一个空值。

有没有办法在纯JS环境下解决这个问题?

I want to get a response(HTML) from a URL with no endpoint. So I sent HTTP requests using the Fetch API, but it continues to return a null value.

通过使用,mode: "no-cors" 你会得到一个不透明的响应,并且无法使用 JavaScript 访问。

因此,如 here 所述,您应该得到一个空值。

如果站点在其响应中发送 Access-Control-Allow-Origin header,只有前端 JavaScript 代码才能直接访问该站点的响应。

而且,您尝试访问的网站 (google) 不会发送该信息。

Is there a way to solve this problem in the pure JS environment?

您可以访问允许它的站点的响应或配置您的后端以发送 Access-Control-Allow-Origin header.

例如这个片段有效,

async function testResponse() {
    let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    let json = await response.json()
    console.log(json)
}

testResponse()

但是,如果您想从不允许的站点访问响应,CORS proxy 可能会有所帮助。 this 答案中提供了详细信息。


此外,fetch 使用 promised-based API。这意味着你可以像这样使用它,


fetch('https://jsonplaceholder.typicode.com/todos/1')
.then( response => console.log(response) )

或者,

async function test() {
    let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    console.log(response)
}

test()

无需同时使用。