[英]Failed to fetch API on CodeSandbox.io with ERR_CERT_COMMON_NAME_INVALID?
I was able to run it as a local app on http://localhost:3001
using npm start
, but if it is used on CodeSandbox or Stack Overflow snippet, the fetch fails.我可以使用
npm start
在http://localhost:3001
上将其作为本地应用程序运行,但如果它用于CodeSandbox或 Stack Overflow 片段,则获取失败。 The same if I use the other API http://worldtimeapi.org/api/timezone/America/Los_Angeles如果我使用其他 API http://worldtimeapi.org/api/timezone/America/Los_Angeles 也是一样
The error:错误:
GET https://worldclockapi.com/api/json/pst/now net::ERR_CERT_COMMON_NAME_INVALID
Seems like it may be due to webpage on https and fetching data from API using http.似乎这可能是由于 https 上的网页和使用 http 从 API 获取数据所致。
Example here as a live Stack Snippet:此处作为实时堆栈片段的示例:
function App() { const [data, setData] = React.useState({}); React.useEffect(() => { fetch("http://worldclockapi.com/api/json/pst/now").then(res => res.json()).then(dataFetched => { setData(dataFetched); }); }, []); return ( <div className="App"> <pre className="data"> {data.currentDateTime} </pre> </div> ); } ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class='react'></div>
Anybody know why and how to make it work?有人知道为什么以及如何使其工作吗?
This looks to be a result of HTTPS security.这看起来是 HTTPS 安全性的结果。
On codesandbox, and here on Stack Snippets, the protocol is https .在 Codesandbox 和 Stack Snippets 上,协议是https 。 HTTPS pages may only make requests to other HTTPS endpoints.
HTTPS 页面只能向其他 HTTPS 端点发出请求。 Since the endpoint on worldclockapi you're using is on HTTP, the browser will not try to connect via HTTP.
由于您使用的 worldclockapi 上的端点位于 HTTP 上,因此浏览器不会尝试通过 HTTP 进行连接。
It may try to upgrade to HTTPS in case the server supports it, but in this case, it doesn't;如果服务器支持它,它可能会尝试升级到 HTTPS,但在这种情况下,它不支持; worldclockapi doesn't support HTTPS at all.
worldclockapi 根本不支持 HTTPS。
In contrast, if you run the code on a local file, that local file is not loaded over HTTPS, so the restriction doesn't apply;相反,如果您在本地文件上运行代码,则该本地文件不会通过 HTTPS 加载,因此该限制不适用; the request to the HTTP endpoint is permitted.
允许对 HTTP 端点的请求。
The best solution would be to find a time API that that supports HTTPS;最好的解决方案是找到一个支持 HTTPS 的时间 API; worldclockapi does not appear to be a good choice at the moment, at least not until they upgrade or fix their SSL configuration.
worldclockapi 目前似乎不是一个好的选择,至少在他们升级或修复他们的 SSL 配置之前不是一个好的选择。 You could also downgrade your server hosting this React app to HTTP, but that's a really bad approach.
您还可以将托管此 React 应用程序的服务器降级为 HTTP,但这是一个非常糟糕的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.