如果服务器存在 JavaScript 而没有 CORS,有什么方法可以有效地记录?

Any way to efficiently log if a server exists with JavaScript without CORS?

我几乎一整天都在尝试在我的 React 代码中实现一个相当简单的功能。基本思想是检查服务器是否可达,如果不可达,则 return a console.log() 指示如此。这是我目前所拥有的:

相关代码

const handleLinkRegex = () => {
    fetch(LinkInput, { mode: "no-cors" })
      .then((response) => {
        if (response.ok || response.status === 0) {
          console.log("yessir");
        } else if (response.status === 404) {
          return Promise.reject("error 404");
        } else {
          return Promise.reject("some other error: " + response.status);
        }
      })
      .then((data) => console.log("data is", data))
      .catch((error) => console.log("error is", error));
  };

输出

如果link有效,如https://mantine.dev/core/input/,则结果为yessir,后跟data is undefined

如果 link 无效并且 return 是 404,例如 https://mantine.dev/core/input/invalidurl,结果是控制台 404 错误,并且 yessir,后跟 data is undefined,这和没失败是一样的。

我试过的

  1. 使用 url-exist 库只会导致 CORS 错误
  2. 尝试使用与 Whosebug 问题不同的解决方案:
const handleLinkVerify = async () => {
    fetch(LinkInput, { mode: "no-cors" })
      .then((r) => {
        console.log("Is reachable");
      })
      .catch((e) => {
        console.log("Is not there");
      });
  };

这导致每个 url,无论是否有效,都 return 为 Is not there

总的来说,我正在挥舞着白旗处理一个简单的问题。我花了好几个小时才发现并处理这个 404 错误,而且无论我读到什么绿色复选标记答案,他们的解决方案都对我不起作用,出于某种原因。我觉得我错过了一些明显的东西,但我不知道是什么。感谢您的帮助。

由于无法将 CORS-Error 与任何其他错误区分开来,假设是 Network-Error,您甚至无法阅读 Status-Code,所以您不能判断网站是否发送了 404 或任何其他代码,您想要采用的方法(在 front-end 上进行检查)在技术上是不可能的。 CORS 是专门为这种行为而设计的。如果您想了解更多相关信息:Trying to use fetch and pass in mode: no-cors

你最好的选择是在后端做这种事情,因为你可以忽略 cors header 并只读取数据。你可以这样做:

我用的是express和axios,大家可以随便用

const express = require("express");
const app = express();
const axios = require("axios");

app.use(express.json());

app.post("/checkStatusCode", async (req, res) => {
  const { url } = req.body;
  if (url == undefined || typeof url != "string") {
    return res.status(400).json({ status: 400, msg: "URL required" });
  }
  try {
    const request = await axios.get(url);
    res.status(request.status).json({ url, status: request.status, msg: request.statusText });
  } catch (err) {
    if (err.response != undefined) {
      res.status(err.response.status).json({ url, status: err.response.status, msg: err.response.statusText });
    } else {
      console.log(err);
      res.status(500).json({ status: 500, msg: "Internal Server Error" });
    }
  }
});

app.listen(5000);

然后您只需在前端调用它,并检查状态代码:

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  "url": "https://google.com"
});

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("http://localhost:5000/checkStatusCode", requestOptions)
  .then(response => response.json())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

如果您在后端遇到 CORS 问题,可以使用一个 npm 包:https://www.npmjs.com/package/cors

只需像这样要求和使用它:

const cors = require("cors");
app.use(cors());