Setting up a .NET Core API and React.js Frontend

The following presumes you have the .NET Core 2.2 SDK, Node.js, and create-react-app installed. If you do not, take a moment to install before progressing.

Somewhere on your machine, create a folder, I’m going to create TestApp. Using the command line, navigate into this directory, as that’s where we’re going to create the two applications.

To create the .NET app named TestApi in a folder named server, simply run dotnet new webapi -n TestApi -o server

Similarly, to create a React app named client in a folder by the same name, run npx create-react-app client

When that’s finished, you’ll need to open up the React App’s package.json and add the following at the end: "proxy": "https://localhost:5001"

The reason we have to add the proxy directive is because, at least by default, the .NET API will run on https://localhost:5001 whereas the Webpack Dev Server will run your react app on http://localhost:3000, and so we need to instruct it where to proxy API requests to. Deploying to a server is a topic for another time.

To test this out, you’ll need two command line windows. The first in TestApp/server where you’ll need to run dotnet run, the second in TestApp/client where you’ll need to run npm run start.

Then, in your React app, probably in App.js, you can make a call to the API like so

import React, { useEffect } from 'react';
import './App.css';

function App() {
useEffect(async () => {
const response = await fetch('/api/values');
const data = await response.json();
console.log(data);
});

return (
<div className="App">
{/** omitted */}
</div>
);
}
export default App;

With this, when your component mounts, it will fire off that request to the .NET API and send the response through to the console.

Leave a Reply

Your email address will not be published. Required fields are marked *