如何处理“不透明"类型的获取响应? [英] how to process fetch response from an 'opaque' type?

查看:166
本文介绍了如何处理“不透明"类型的获取响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试正确解释从对URL的提取调用中得到的响应,我认为这是一个json字符串.我已经根据这里的类似帖子尝试了许多变体,但是没有任何东西可以帮助我获得有用的数据.这是一种尝试:

I'm trying to correctly interpret the response from a fetch call to an URL, that I think is a json string. I've tried a many variations based on similar posts here, but nothing is getting me useful data to work with. Here is one attempt:

fetch('http://serverURL/api/ready/', {method: "POST", mode: "no-cors"})
    .then(function(response) { 
        response.json().then(function(data) {
            console.log('data:' + data);
        });
    })
    .catch(function(err) {
        console.log('Fetch Error :-S', err);
    });

这将在控制台中返回语法错误:

This returns a syntax error in the console:

SyntaxError:JSON.parse:的第1行第1列的数据意外结束 JSON数据

SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

所以它可能不是JSON ...如果我在console.log行上放置一个断点,并将鼠标悬停在响应(上面的行)上,则会看到响应对象(?)带有多个字段:

So maybe its not JSON...if I put in a breakpoint on the console.log line, and hover over response (line above), I see the response object (?) with various fields:

不确定如何解释... status:0表示它没有得到有效的响应.但是,如果我检查开发人员工具中的网络"选项卡,然后单击获取"行,状态为200,并且响应"窗口/JSON部分显示了消息信息,您也可以看到是否只是将URL放入浏览器URL直接吧.就像响应有效负载"部分一样,该部分显示了JSON字符串:

Not sure how to interpret that...status:0 suggests it did not get a valid response. However, if I check the Network tab in the developer tools, and click on the fetch line, status there is 200, and the Response window/JSON section shows the message info that you also see if you just put the URL into the browser URL bar directly. As does the "Response payload" section, which shows the JSON string:

{"msg":"API就绪.",成功":true}

{"msg": "API is ready.", "success": true}

所以...看起来像json,不是吗?但是fetch无法将其作为json吸收?

So...it looks like json, no? But fetch is unable to ingest this as json?

这是另一个变体,但是使用response.text()而不是response.json()

Here's another variation, but using response.text() instead of response.json()

fetch('http://serverURL/api/ready/', {method: "POST", mode: "no-cors"})
    .then((response) => {
        console.log(response);
        response.text().then((data) => {
            console.log("data:" + data);
    });
});

这将在控制台中打印响应对象(与上面相同:确定:false,状态0,类型:不透明等).第二个console.log文件在data:之后不打印任何内容.如果我使用response.json,则会再次收到关于数据结尾的语法错误,如上所述.

This prints the response object in the console (same as above: ok: false, status:0, type:opaque etc). The second console.log file prints nothing after data:. If I use response.json, again I get the syntax error about end of data as above.

有什么想法吗?我意识到服务器可能没有提供获取所需的信息,但它确实提供了一些信息(至少在直接在浏览器中使用URL时),这就是我需要处理的信息,例如json或文本或其他信息.

Any ideas? I realize the server may not be providing what fetch needs or wants, but, it does provide some info (at least when using the URL directly in the browser), which is what I need to then deal with, as json or text or whatever.

推荐答案

基本上,您无法访问来自不透明请求的响应正文.

Essentially, you cannot access response body from an opaque request.

添加模式:"no-cors"不会神奇地使事情正常运行.浏览者 默认块前端代码无法跨资源访问资源.如果 站点在其响应中发送Access-Control-Allow-Origin,然后 浏览器将放松该阻止,并允许您的代码访问 响应.

Adding mode: 'no-cors' won’t magically make things work. Browsers by default block frontend code from accessing resources cross-origin. If a site sends Access-Control-Allow-Origin in its responses, then browsers will relax that blocking and allow your code to access the response.

但是,如果网站未在其中发送Access-Control-Allow-Origin标头 它的响应,那么您的前端JavaScript代码就无法 直接访问该站点的响应.特别要指出的是 模式:无心"不会解决该问题(实际上只会使情况变得更糟).

But if a site doesn’t send the Access-Control-Allow-Origin header in its responses, then there’s no way your frontend JavaScript code can directly access responses from that site. In particular, specifying mode: 'no-cors' won’t fix that (in fact it’ll just make things worse).

来自 https://stackoverflow.com/a/43268098/1666071

也来自fetch文档:

no-cors-防止该方法成为HEAD,GET之外的任何其他方法 或POST,并且标头不是简单的 标头.如果任何ServiceWorkers拦截了这些请求,则他们可能不会 添加或覆盖除简单标头之外的所有标头. 此外,JavaScript可能无法访问结果的任何属性 响应..这确保ServiceWorkers不影响语义. 并防止由于以下原因引起的安全和隐私问题 跨域泄漏数据.

no-cors — Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers. If any ServiceWorkers intercept these requests, they may not add or override any headers except for those that are simple headers. In addition, JavaScript may not access any properties of the resulting Response. This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains.

https://developer.mozilla.org/zh- US/docs/Web/API/Request/mode

这篇关于如何处理“不透明"类型的获取响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆