当我创建和使用新控制器时,它似乎无法接近控制器。
这是源代码,我创建了“图书控制器”。控制台错误是“Uncaught(承诺) SyntaxError:在JSON中位于0位置的意外令牌”
export class BooksIndex extends Component {
constructor(props) {
super(props);
this.state = {
books: [],
loading: true
}
}
// page initialized
componentDidMount() {
this.populateBooksData();
}
static renderBooksTable(books) {
return (
<table className='table table-striped' aria-labelledby="tabelLabel">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Created</th>
</tr>
</thead>
<tbody>
{books.map(book =>
<tr key={book.id}>
<td>{book.id}</td>
<td>{book.title}</td>
<td>{book.description}</td>
<td>{book.created}</td>
</tr>
)}
</tbody>
</table>
);
}
render() {
let content = this.state.loading
? <p><em>Loading...</em></p>
: BooksIndex.renderBooksTable(this.state.books);
return (
<div>
<h1>My Books</h1>
<h2>This is my book</h2>
{content}
</div>
);
}
async populateBooksData() {
const response = await fetch("books");
const data = await response.json();
this.setState({ books: data, loading: false });
}
}cf)这是项目执行时的截图。WhetherWebcaster是在创建项目时默认创建的控制器。
发布于 2022-05-28 12:11:55
如果您通过dotnet new react使用react模板,那么可能是因为ClientApp/src中的setupProxy.js中的上下文,默认情况下如下所示:
const context = [
"/weatherforecast",
];
module.exports = function(app) {
const appProxy = createProxyMiddleware(context, {
target: target,
secure: false,
headers: {
Connection: 'Keep-Alive'
}
});
app.use(appProxy);
};您可以将/books添加到上下文数组中,或者,正如我建议的那样,只需将其更改为/api,然后在控制器上使用该属性(或创建其他人继承的基本控制器):[Route("api/[controller]")]
https://stackoverflow.com/questions/72414569
复制相似问题