简体   繁体   中英

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. The same if I use the other 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.

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.

On codesandbox, and here on Stack Snippets, the protocol is https . HTTPS pages may only make requests to other HTTPS endpoints. Since the endpoint on worldclockapi you're using is on HTTP, the browser will not try to connect via HTTP.

It may try to upgrade to HTTPS in case the server supports it, but in this case, it doesn't; worldclockapi doesn't support HTTPS at all.

在此处输入图像描述

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; the request to the HTTP endpoint is permitted.

The best solution would be to find a time API that that supports HTTPS; worldclockapi does not appear to be a good choice at the moment, at least not until they upgrade or fix their SSL configuration. You could also downgrade your server hosting this React app to HTTP, but that's a really bad approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM