Home > Blockchain >  react asp.net core (.net 6) create new controller
react asp.net core (.net 6) create new controller

Time:05-29

When I create and use new controller, It looks like can not approach the controller.

This is source and I creacted 'BooksController'. And console error is 'Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 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) This is a screenshot when the project execute. WhetherWebcaster is a controller created by default when a project is created.

enter image description here

CodePudding user response:

If you used the react spa template via dotnet new react, then it's probably because of the context in the setupProxy.js in ClientApp/src which by default looks something like this:

const context =  [
  "/weatherforecast",
];

module.exports = function(app) {
  const appProxy = createProxyMiddleware(context, {
    target: target,
    secure: false,
    headers: {
      Connection: 'Keep-Alive'
    }
  });

  app.use(appProxy);
};

You can either add /books to that context array or, as I would suggest, just change it to /api and then use this attribute on your controllers (or create a base controller that the others inherit from): [Route("api/[controller]")]

  • Related