next.js React无法从Web API获取数据[已关闭]

tvmytwxo  于 2023-05-06  发布在  React
关注(0)|答案(1)|浏览(177)

**关闭。**此题需要debugging details。目前不接受答复。

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答这个问题。
15天前关闭。
Improve this question
我在web-api中有以下控制器,我正在使用React v18.2.0和NextJS v13.3.0:

public List<ReturnDat> Get()
    {
        List<ReturnDat> lst = new List<ReturnDat>();

        lst.Add(new ReturnDat() { 
        ID = 1,
        Title = "Title -1 "
        });

        return lst;
    }

下面的类:

public class ReturnDat
    {
        [DataMember(EmitDefaultValue = false)]
        public int ID { get; set; }

        [DataMember(EmitDefaultValue = false)]
        public string Title { get; set; }
    }

这是WebApiConfig.cs

config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings
.Add(new System.Net.Http.Formatting.RequestHeaderMapping("Accept",
                              "text/html",
                              StringComparison.InvariantCultureIgnoreCase,
                              true,
                              "application/json"));

React:

const[data,setData] = useState([]);
  const[num,setNum] = useState(1);
  
  const fetchData = async () => {
    const response = await fetch("https://localhost:44346/api/values/");
    //https://swapi.dev/api/people/1/
    const newData = await response.json();

  };
  
useEffect(() =>{


  fetchData();});

问题是API被命中并到达return语句,但从React方面来说,它说:类型错误:取失败。
用同样的代码,我尝试了这个API(我在网上找到的,不是我做的)***https://swapi.dev/api/people/1/***,代码运行良好!所以我怀疑我需要做一些配置我的API,所以我尝试
1.添加和删除[DataMember]
1.在web API的配置文件中添加和删除JSON格式。
1.已更改返回类型。
什么都不管用!
然后我使用NextJS getServerSideProps(),数据从API返回。
问题可能是什么,如何解决?
这是网络选项卡中返回的内容:

gev0vcfq

gev0vcfq1#

请注意,useEffect可以用于client-side rendering (CSR),而getServerSideProps用于服务器端渲染(SSR),这是data fetching in Next.js的两种不同方法。
该错误可能与后端应用程序中的Access-Control-Allow-Origin或其他CORS配置有关。

相关问题