当我创建并使用新的控制器时,看起来不能接近控制器
这是源代码,我创建了'BooksController'。控制台错误是'Uncaught (in promise) SyntaxError: Unexpected token <</p>
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)这是项目执行时的屏幕截图。是否为创建项目时默认创建的控制器。
输入图片描述
如果你通过dotnet new react
使用了react spa模板,那么它可能是因为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]")]