我花了几乎一整天的时间,只是试图在我的React代码中实现一个相当简单的功能。其基本思想是检查服务器是否可访问,如果不可访问,则返回一个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));
};
输出如果链接是有效的,例如https://mantine.dev/core/input/
,则结果是yessir
,然后是data is undefined
。
如果链接无效并返回404,例如https://mantine.dev/core/input/invalidurl
,则结果是控制台404错误,然后是yessir
,然后是data is undefined
,这与没有失败一样。
What I tried
- 使用
url-exist
库只会导致CORS错误 - 试图使用与stackoverflow问题不同的解决方案:
const handleLinkVerify = async () => {
fetch(LinkInput, { mode: "no-cors" })
.then((r) => {
console.log("Is reachable");
})
.catch((e) => {
console.log("Is not there");
});
};
这导致每个url,无论是否有效,返回为Is not there
。
总的来说,我在处理一个简单的问题时挥舞着白旗。我花了几个小时来捕捉这个404错误并处理它,无论我读到什么绿色复选标记的答案,他们的解决方案都不适合我,出于某种原因。我觉得我错过了一些明显的东西,但我不知道是什么。谢谢你的帮助。
由于不可能将CORS-Error与任何其他错误(假设是Network-Error)区分开来,并且您甚至无法读取状态码,因此您无法判断网站是否发送了404或任何其他代码,因此您想要的方法(在前端检查)在技术上是不可能的。CORS就是专门为这种行为设计的。如果你想了解更多:尝试在mode: no-cors
中使用fetch和pass你最好的选择是在后端做这类事情,因为你可以忽略cors头,只读取数据。你可以这样做:
我用了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);
然后你只需在你的前端调用它,并检查Statuscodes:
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());