繁体   English   中英

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

[英]Fetch data from api in createContext using Fetch api in React doesn't work

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

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文件,并使用该fetchData()使用useEffect的内context 应该改什么代码?

尝试了以下操作,但没有用,甚至无法打印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));
}

CORS 问题。 尝试为 CORS 放置标头:请参阅此链接以获得明确的答案: https : //stackabuse.com/handling-cors-with-node-js

如果没有 CORS 设置,您的 Reactjs API 将被阻止,您可以检查控制台。 它会抛出: net::ERR_FAILED

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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