代码之家  ›  专栏  ›  技术社区  ›  copenndthagen

如何处理无内容获取的错误?

  •  0
  • copenndthagen  · 技术社区  · 4 年前

    我有一个取回请求,如下所示;

    fetch(url, {
        mode: 'no-cors',
        credentials: 'include'
    }).then((response) => {
        if (response.ok) {
            return;
        }
        console.log(`Something wrong`);
    })
    .catch((error) => {
        console.log(`catch block error`);
    });
    

    我的回答似乎是

    body: null
    bodyUsed: false
    headers: Headers {}
    ok: false
    redirected: false
    status: 0
    statusText: ""
    type: "opaque"
    url: ""
    

    我的问题是如何处理这个问题,因为我的204响应是成功的,但唯一的问题是ok标志是错误的 因此,它会打印出“有问题”的内容,而这对于204响应来说是不正确的。

    3 回复  |  直到 4 年前
        1
  •  3
  •   Quentin    4 年前

    你说 mode: 'no-cors' 所以你不能看答案。 no-cors 模式仅在以下情况下有用:

    • 你需要发送一个请求
    • 该请求不需要任何使其预飞的功能
    • 你不需要知道任何关于回复的信息

    您无法读取状态(这就是为什么报告为 0 在你引用的回复中),所以你不知道这是不是 204 No Content 200 OK 500 Internal Server Error

    你无法阅读身体,因此你无法通过测试来判断是否没有内容。


    你需要:

    • 去除 模式:“没有cors”
    • 确保服务器授予您使用CORS所需的所有权限
    • 阅读 status 属性,以确定它是否为 204 还是不行