简体   繁体   中英

Why do I get JSON.parse error when using default code from “dotnet new react -o my-app”?

Running the terminal command 'dotnet new react -o my-app' builds a C# React app, but when testing the starting files it doesn't work. Running 'npm start' from the my-app/ClientApp directory starts the app but navigating to the page http://localhost:3000/fetch-data you get the console error:

"SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data"

This is the block of code that it never gets past:

constructor(props) {
super(props);
this.state = { forecasts: [], loading: true };

fetch('api/SampleData/WeatherForecasts')
  .then(response => response.json())
  .then(data => {
    this.setState({ forecasts: data, loading: false });
  });
}

It calls this controller, but the code in it never runs:

[Route("api/[controller]")]
public class SampleDataController : Controller
{
    [HttpGet("[action]")]
    public IEnumerable<WeatherForecast> WeatherForecasts()
    {
        Console.WriteLine("I NEVER GET CALLED");
        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            DateFormatted = DateTime.Now.AddDays(index).ToString("d"),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        });
    }

I'm using these docs to build the app:

https://docs.microsoft.com/en-us/aspnet/core/client-side/spa/react?view=aspnetcore-3.0&tabs=netcore-cli

I plan to use this as a scaffold to build a new app, but I'm concerned that it isn't working before I've done any coding to it. Does anyone know why or how to fix it?

You get the error because NODEJS (NPM START) isn't designed to host .NET, and the API call written in c#, is AspNet, AspNetCore, etc. As an aside, NPM START kicks off resources located in the package.json file, and that file makes no reference to the Microsoft portion of the overall solution (yes the Microsoft article from which you are working is someone confusing since it doesn't directly point that out).

IIS (or in this case Microsoft Internet Information Services Express ) can host both React and the API because the Startup.cs file and AspNetCore are configured to do so.

Real world, we typically generate our API's under one project, while building our UI application under another, each hosted on a unique Port, which at a minimum, offers a big plus by being able to test the API / UI independently (well, the API independently anyway - you can test the UI without the API as well but without API data, it's not always practical).

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