[英]How do I deal with a JSON.parse error coming from a Test in react when trying to mock localStorage?
[英]Why do I get JSON.parse error when using default code from “dotnet new react -o my-app”?
運行終端命令 'dotnet new react -o my-app' 會構建一個 C# React 應用程序,但是在測試啟動文件時它不起作用。 從 my-app/ClientApp 目錄運行“npm start”會啟動應用程序,但導航到頁面http://localhost:3000/fetch-data會出現控制台錯誤:
“語法錯誤:JSON.parse:JSON 數據的第 1 行第 1 列出現意外字符”
這是它永遠不會通過的代碼塊:
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 });
});
}
它調用此 controller,但其中的代碼從未運行:
[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)]
});
}
我正在使用這些文檔來構建應用程序:
我計划將其用作構建新應用程序的腳手架,但我擔心在我對其進行任何編碼之前它無法正常工作。 有誰知道為什么或如何解決它?
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,並且該文件未提及整體解決方案的 Microsoft 部分(是的,您正在工作的 Microsoft 文章令人困惑,因為它沒有直接指出這一點)。
IIS (或在本例中為Microsoft Internet Information Services Express )可以同時托管React和 API,因為Startup.cs文件和AspNetCore已配置為這樣做。
在現實世界中,我們通常在一個項目下生成我們的 API,同時在另一個項目下構建我們的 UI 應用程序,每個都托管在一個唯一的端口上,這至少通過能夠獨立測試API / UI來提供很大的優勢(嗯, API 無論如何都獨立 - 您也可以在沒有 API 但沒有 API 數據的情況下測試 UI,這並不總是實用的)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.