如何处理来自“不透明"类型的获取响应?

2023-10-02前端开发问题
8

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

问题描述

我正在尝试正确解释从 fetch 调用到 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 表明它没有得到有效响应.但是,如果我检查开发人员工具中的 Network 选项卡,然后单击 fetch 行,状态为 200,并且 Response 窗口/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 准备就绪.", "success": 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);
    });
});

这会在控制台中打印响应对象(与上面相同:ok: false、status:0、type:opaque 等).第二个 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.

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

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 代码就无法直接访问该站点的响应.特别是,指定mode: 'no-cors' 不能解决这个问题(事实上它只会让事情变得更糟).

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 可能不会访问结果的任何属性响应. 这可确保 ServiceWorker 不会影响语义Web 和防止安全和隐私问题引起的跨域泄露数据.

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/en-US/docs/Web/API/Request/mode

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

The End

相关推荐

Fatal error: Call to a member function fetch_assoc() on a no
业务场景:使用update语句去更新数据库字段。 原因:update接收值不正确。原来代码: $query = "UPDATE student SET date = now() WHERE id = $id";$result = $mysqli-query($query2) or die($mysqli-error); // 问题出现了在这句 $data = $result-fetch_ass...
2024-12-13 前端开发问题
136

ajax请求获取json数据并处理的实例代码
ajax请求获取json数据并处理的实例代码 $.ajax({ type: 'GET', url: 'https://localhost:44369/UserInfo/EditUserJson',//请求数据 data: json,//传递数据 //dataType:'json/text',//预计服务器返回的类型 timeout: 3000,//请求超时的时间 //回调函数传参 suc...
2024-11-22 前端开发问题
215

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301

JavaScript(js)文件字符串中丢失"\"斜线的解决方法
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转...
2024-10-17 前端开发问题
437

layui中table列表 增加属性 edit="date",不生效怎么办?
如果你想在 layui 的 table 列表中增加 edit=date 属性但不生效,可能是以下问题导致的: 1. 缺少日期组件的初始化 如果想在表格中使用日期组件,需要在页面中引入 layui 的日期组件,并初始化: script type="text/javascript" src="/layui/layui.js"/scrip...
2024-06-11 前端开发问题
455