【发布时间】:2019-12-22 06:48:03
【问题描述】:
我正在学习如何使用 ASP.NET Core 创建 React 应用程序。作为一个新手,我从一开始就尝试在主页上显示“Hello World”。我已经使用 Visual Studio 的默认 React.js 项目模板来帮助我入门。路由设置为默认值。这是我的文件:
Home.js:
import React, { Component } from 'react';
export class Home extends Component {
constructor(props) {
super(props);
this.state = { message: "" };
fetch('api/Home/Message')
.then(response => response.json())
.then(data => {
this.setState({ message: data });
});
}
render () {
return (
<h1>{this.state.message}</h1>
);
}
}
HomeController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace TestingReactDotNet.Controllers
{
[Route("api/[controller]")]
public class HomeController : Controller
{
[HttpGet]
public async Task<IActionResult> Message()
{
var response = "Hello World";
return Ok(response);
}
}
}
问题在于被解析为 Json 的 HTTP 响应不是正确的。我已将其 console.logged 以尝试调试,似乎response.json()) 正在检索模板应用程序附带的默认public/index.html 文件中的所有文本。有谁知道这是为什么?
如果我遗漏了一些非常明显的东西,我深表歉意 - 我使用的是 Mac,因此文件结构和 Visual Studio IDE 完全不同,我已经很难理解其中的很多教程/答案。
【问题讨论】:
-
你能解决这个问题吗?在点击控制器方法时我遇到了同样的问题。我收到“您需要启用 JavaScript 才能运行此应用程序”。这是 react app @juemura7 中 index.html 的默认消息
-
嗨@DevProf - 在我的例子中,我用
public string Message()替换了public async Task<string> Message()
标签: c# reactjs model-view-controller routing