在 React 中使用 Fetch api 从 createContext 中的 api 获取数据不起作用



我有一个现有的产品context。最初,我使用了一些模拟数据,如下面的STORE_DATA所示来渲染组件。现在,我需要替换那个模拟数据,并连接到local port上可用的Node.jsapi(在创建react-app之后创建了api I(。

import React, { createContext, useState } from 'react';
import STORE_DATA from '../shop';
export const ProductsContext = createContext();
const ProductsContextProvider = ({ children }) => {
const [products] = useState(STORE_DATA);
return (
<ProductsContext.Provider value={{ products }}>
{
children
}
</ProductsContext.Provider>
);
}
export default ProductsContextProvider;

刚刚创建了一个带有以下内容的helper.js文件来获取数据:

import {useEffect} from "react";

const fetchData = () => {
return fetch("https://localhost:8081/products") <<tested on postman and works fine.
.then((response) => response.json())
.then((data) => console.log('Fetching Data:',data));
}

如何替换context文件上的模拟数据,并在context中使用useEffect来使用此fetchData()?应该更改哪些代码?

尝试了以下操作,但没有成功,甚至无法打印console.log:

import React, { createContext, useState, useEffect } from 'react';
import { fetchData } from '../helpers';
export const ProductsContext = createContext();
const ProductsContextProvider = ({ children }) => {
const [products, setProducts] = useState(null);
useEffect(() => {
setProducts(fetchData());
}, []);
return (
<ProductsContext.Provider value={{ products }}>
{
children
}
</ProductsContext.Provider>
);
}
export default ProductsContextProvider;

问题是它返回了以下错误(已解释(:

net::ERR_SSL_PROTOCOL_ERROR (on chrome)

解决方案:在以下代码中的URL中使用http://而不是https://

const fetchData = () => {
return fetch("http://localhost:8081/products") 
.then((response) => response.json())
.then((data) => console.log('Fetching Data:',data));
}

最新更新