How to connect my c# backend with the frontend?
Hello, I created a ASP NET Core Web Api project with the command dotnet new webapi -minimal. In my program.cs I am fetching some data from a public server and displaying it in plaintext for now when I run it and open localhost.
So it works perfectly but since I am a beginner I have two questions.
1. Is my code and approach fine the way I did it? Is there anything what I can improve?
2. How can I connect this with a React frontend to display the some values from the fetch? I know how to work with react but I am missing the link how to connect each other?
I uploaded the code on github here: https://github.com/BearCooder/ASP.NET-Core
Basically the code is only in program.cs
I appreciate any help!
13 Replies
manually adding a react app to an existing asp.net project can be a bit of a hassle, if you have VS or Rider there should be templates for ASP projects that include react
It would probably be easier for you to create a new project (that supports react already) and then copy your existing code over
Ah I did not know this. I use VSCode. I was looking for a best practice how to work with c# and react but at the end I was not sure whats the right approach to be honest
I would personally recommend using a proper IDE instead of VSCode for working with c#
but there are probably ways to create templated projects from the CLI
There are, it's a template of its own
However you don't need to use that template. It's very common to simply run your react app on its own
Set up a dev proxy to redirect your api traffic, and thats all you need
So you mean something like adding a proxy in my package json where my react app e.g. "proxy": "http://localhost:5000"? And using the port where my ASP NET Core app is running.
Yeah, something like that
We use vite at work and have that setup
It works great
Ok that sounds good I also use Vite with React. And then I should be able to display certain data with axios?
well, axios lets you make requests to the backend, yes
then you do react stuff with that data to show it 🙂
Or you can ditch Axios and just use
fetch()
¯\_(ツ)_/¯Yes true. I just have a problem to make a successfull request to my ASP NET Core app to see the data on the frontend. And I was trying either with axios or fetch.
This is what I try in React. The backend code is in my program.cs in the github link. No matter what I try I get TypeErrors in browser console. And now its patient.name.given is undefined.
so log the result you're getting from the fhir api and make sure it contains what you're expecting?
https://github.com/BearCooder/ASP.NET-Core/blob/cacc0433de246c61d75df2d0ca7790aaa007459a/Program.cs#L27 if this is still how you have it written, I would expect things to fail
GitHub
ASP.NET-Core/Program.cs at cacc0433de246c61d75df2d0ca7790aaa007459a...
Contribute to BearCooder/ASP.NET-Core development by creating an account on GitHub.
you aren't returning a valid json object here