Create React App with an Express Backend
HTML-код
- Опубликовано: 7 фев 2025
- Learn how to wire up a React app to fetch data from an Express server in 5 minutes.
And, if your backend is not written with Express, this same "proxy" setting will work for you too. Read the blog post here: daveceddia.com...
Got it working and want to deploy to Heroku? Check out this post: daveceddia.com...
Finally a f*** good video that explains howto connect the two. to hell with those 5 hour tutorial that are worth s***
Hhaahah trust me man! Sick and tired of these hour long livestreams.
AGREE!!!!
I would love if there were more videos this simple and to the friggin point.
its almost 2022 and this is still the most simple to the point video that exists on RUclips. thank you.
Absolutely the best template out there to follow. I have spent countless hours just trying to follow articles and getting nowhere
Pretty the same! Thanks Dave.
Setting up that proxy is the key if you already know Express.js and React, but I'm still amazed that you showed us the meat in just over 5 minutes. The only thing I'm sad about is that you don't have more videos.
Thanks dudee, at last i nailed it after watching a thousands of videos about react - express connection .
Only just spotted this video (late) last night.
Gave it a try this afternoon. 20 minutes, some missing }'s and my longer running learn-React-project now has a backend. Awesome video!
Now on to deploying to Heroku :)
Thanks man! You've created the best React/Express intro on RUclips.
Amazing! I just needed a simple practical example of how to fetch data from db and update the state with fetched data! Agree with other comments how straightforward your tutorial was!
You are the hero that we need, not the one we deserve! I spent more time opening links on Google than I did learning how to connect React App to my Express back end from this video. If only every resource was this focused.
Hoping to see more content from you!
Amazing tutorial man. It was short and simple :) Thanks alot
the best express course I've ever seen! Fast, simple, informative. Thank you very very!
Good frickin job man! Thank you for turning my afternoon of learning into 5 minutes. And to think this could've been a 20 part series
Thanks, glad it was helpful! Really not a fan long-winded tutorials myself haha.
Like others already mentioned... Concise and straight to the point. Thanks a bunch.
the best short explanation ever
Fantastic video mate! You have helped me understand react and express it better then my Bachelor in CS did.
Thank you, glad it helped!
Dang we need more tutorials like this!
No bs, straight to the point. YES!
greatest tutorial i've ever seen about anything, thanks
Short and sweet! Loved it
fastest Ive seen yet lol thanks
Thank you Dave Ceddia, good and concise tutorial.
Super helpful video!! Thank you so much, really appreciate how short and to the point it is
Thank you dave! The video was straightforward and excellent
Simple, yet effective, no bullshit.
short and simple ..thank You
Thia tutorial is actually pretty good 👍
BLESS YOUR SOUL MAN
thanx buddy , u're a savior 🔥🔥🧡
Awesome. Very clear explanation and quick too. Keep it up.. Thanks a ton.
clear and to the point! subscribed!
So simple. Thank you. 😊
Hey dude! Finally a great video explaining exactly what Ive been looking for. Could you also upload a similar video explaining how to do routing ? I have a react-router-v4 set up in my react app, so should I just use that and grab my api from express ? or should I do routing using express as well ?
So just to clarify if you were render react pages using this method, is this still client-side rendering? I suppose it would be unless you were actually serving .html files with express back to the client right?
Yep, this is client-side rendering, because the server is replying with an empty HTML shell + JS and the client fills it in. It would be server-side rendering if Express executed the React code and generated the full HTML on request.
@@dceddia Gotcha, so then going forward, I have tested fetching data from my express endpoints via get requests and it works great.
If I start implementing some UI and web pages now in React, would I still use React's Router to switch components / pages? I imagine that would work and any time I need specific data I just make a fetch request to express right?
Or is using React router completely unnecessary using this method? I'm newer to React by the way, I've used React Native a few times though.
@@SpooningTreesap86 Yeah, React Router will work for switching pages client-side. The catchall "*" route will ensure the server plays along with it, so you get the same index.html + React app no matter which server route you visit, and the client takes over from there and renders the right components to match what's in the address bar.
@@dceddia Awesome, thank you very much for your insight. It's funny I had read two of your blog posts related to this well after watching this video and then when I saw one article had a link to this video I was like ohh shoot I've watched his vid lol
Thanks for the vid! Very helping!
Hey sire !
I was just searching for a solution of an error express gives when I import it in react. Would it fix that ?
Note:Massive errors are thrown back on importing
Not totally sure I understand your question, but I don't think it makes sense to import Express from React code. Express is the server, and the entry point for everything. The other way could make sense, Express importing the React app, for server-side rendering?
This. Is. Perfect. Thank you for the concise lesson. Sub'd.
Is it important to put client inside the server directory?
It can pretty much go anywhere, technically. If the server is serving files from the client build directory, like it is here, it makes sense to keep those files under the server dir somewhere, so that it’s easy to copy the whole client+server bundle up to a server for deployment. If they’re independent - say, if client files are served by S3 and the server is just an API server, it could make sense to separate the directories. The other reason to keep them together is to have a unified build process (one command to build both of them is easier if they share a parent directory!) Depends on the setup of course though.
Best Video! So easy ;) Thank you so much!
This is it. Thank you
I am a little bit confused. We need to start both React and Express applications. Is there any solution to start only Express app without starting React?
During development, you need both: the Express server to serve the API, and the React (webpack) dev server to recompile your front end code as you work. There are ways to combine them, so that the Express server can run Webpack, but it's complex and I don't recommend it. If what you want is to be able to run a single command to start both, have a look at the npm-run-all package.
During production, the webpack dev server is out of the picture. You'll only have the Express server, serving the API and prebuilt files. (In practice, you might want an Nginx webserver serving static files, and proxying API requests to Express.) Either way - those static files will come from the React build (npm run build).
@@dceddia Thanks for your help Dave. Actually I spent a couple of time to work with npm run build as you've recommend. It worked find.
It keeps telling res is undefined when i try to fetch the data...what to do??!
Look for (Ctrl+F) where you’re using “res” and make sure the variable is defined. Sounds like it’s not. Most likely a line that looks like fetch(...).then(res => res.json())
Concise. Thank You!
Despite of adding the "proxy" line in package.json , fetch is still senting the request to localhost:3000 instead of localhost:3001
What could be the issue here? I'm using Windows10 btw
Luis what do your proxy and fetch lines look like?
@@dceddia
Proxy:
"proxy": "localhost:3001"
Fetch:
fetch('/api/stuff')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log('Something went wrong: ', err));
For some reason it is ignoring the package.json line. It keeps sending the request to localhost:3000/api/stuff
Fixed it for the moment by directly adding the full path into the fetch line...
how would I do this and also get twitter api request(e.g trending hashtags) and show it on react app?
Very helpful video, thanks !
I tip my hat to you sir, one subscriber added :)
Thanks Man !
Hello Dave, I have a problem when I try to fetch my API it works, but when I want to map to get a list I got the error -> 'this.state.users.map is not a function'. Do you have any idea why??
this.state.users is probably undefined, or otherwise not an array. Make sure you’re initializing it to an empty array, and make sure when you call setState that the new value is an array too.
@@dceddia thank you for answering first!! Indeed it wasn't an array but I found my solution using 'Object.key()'
Great. Thanks. What's the app you used to create your directory tree view?
The command is "tree" (I ran "tree -I node_modules"). I installed it with Homebrew, "brew install tree".
Nice one. Thanks!
Great tutorial thank you!!!
Maybe add a video about how to design it, so that it can be pushed to production
On Windows, kept getting errors, in the end, I just changed the bin/www file via the editor , and changed the port directly there to 3001. Would there be any reason not to do that?
Exactly what I thought. As a forerunner, did anything break? lol
set port=3001
npm start
Very useful, thanks! :)
May I know what theme are you using for the Chrome browser? @2:02
Reach it’s an extension called Pallettab
Command 'mvim' not found, but there are 30 similar ones.
how to solve this?
You don't have to use mvim to edit the files, that's just what I was using at the time. You can use any editor - VSCode is a popular choice.
I think you should have said to the user who uses CORS for their server they have to restart both their npm start for react and express. I stuck in this for almost 1hr for finding the solution is just restart both npm
I've been there! It sucks! When in doubt, restart everything. Especially if you've changed anything in any of the parts.
@@dceddia yes surely, just suggest to maybe put it in the description for people who does not start their express with express generator. great video anyways, keep it up
Well done!
Hope someone can help me out! if I put an API call into the res.json where he hardcodes data could I get whatever data I needed from my API?
Not sure I’m reading this right (lmk if not) but if you want to make a second API call then yeah you could do it in the .then, or if it doesn’t depend on data from the first call, you could do 2 fetches at the same time (duplicate the whole fetch().then().then() block & change the URL).
so if I understand, you have 2 servers running instead of 1? why not just running 1 server and serve the react js file? I am new to react, so I might be wrong
Im also pretty new to backend, but I think he made two servers for simplicity.. Infact we do need two different servers, where one serves our App, and the other serves our data. I think this can be implemented into one single app, but it would still need two different servers. I THINK...
There are some advantage of using 2 servers. 1 to handle the UI (javascript, css, html) and 1 to handle the back-end, but those type of design are good when you have a team with you. I looked into the documentation and found how to do it
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(9000);
look at
github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md
Classic Man Channel but can't we just achieve this using the way he mentioned here ? Or will using this in a server.js within our react app will do it ?
There is not really a right or wrong solution. Usually, people will do the choice based on their need. I usually host my site in Google Cloud or AWS. since I have to pay for each servers, I would usually try my best to save as much money possible by using the less resources possible. His solution is runing 2 proceses on the server. 1 only take care of generating the css, javascript, html asset. and the other one take care of handling REST request. There is nothing wrong with his solution. At the end of the day, as long as your site is up and runing, everyone is happy.
Nice tutorial! One question: instead of hard-coding the data in the users.js file, how do I import data.json?
If it's on the filesystem, something like `const data = require('./path/to/data.json')` should work. The path is relative to the location of the file doing the requiring. Or if the data is remote, look into the "request" library for Node, it's nice for doing HTTP requests.
Thank you! How to start both express server and react dev server with one command? I mean without using 2 separate terminals for starting each?
Have you find out a way how to do it?
using concurrently
@@rjtorres6099 shell scripting
Hi Dave, Great video very concise. I have an issue which I see you have addressed on your website about json response returning html (Unexpected token < in JSON at position 0). I followed this video for the most part, But already had a create-react-app project created, so I created a separate file which servers the get request and returns your json with similar error. Any idea why I might still be receiving html when I am returning json from my get express call?
I got sorted, I was routing using a default "/" and it was throwing an error even when matched up from front-end to server. Once I added a route that wasn't default e.g. "/data" then everything worked.
how is your app working bro without cors?
Create React App's proxy takes care of that. If you need to set up CORS on Express though, the cors middleware is the way to go: expressjs.com/en/resources/middleware/cors.html
thanks for the video is all good, but what to do to add another fetch('/another url), how to use setState with more resources?
You can store more than one thing in state, like you could have one fetch that does setState({ users: usersFromServer }) and another that does setState({ groups: groupsFromServer }) and they'd happily co-exist, and you could render them in the same component. Another way would be to create a second component that deals with the `/another url`.
Hi Dave, thanks a lot:)) it works, just one doubt at the beginnning of the class App, state= {users= []}, the state it takes the value of the path /users (set state to 'users') and /projects(set state to 'projects') or whatever i want to pull form backend,..and render them on the page, so doesn't have to be called 'users'..can be anything?thank you again
Yes absolutely, there's nothing magical about "users" there. A component's state is just a plain JS object, you can put whatever you want in there, and access it via this.state.whatever. It's good to initialize state before using it, so make sure the state = {...} at the top initializes the keys you use later on.
Million thanks, Dave! That was exactly my question. if you stop by in Rome you have a good pizza and coffee paid. cheers
can i use this at react native ??
please respond :)
update 2021: If you are facing errors such as MIME errors about resource sharing, try these cuz it worked for me
app.get("/users", function (req, res) {
var ejsVar = 'USEssssAME';
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers,X-Access-Token,XKey,Authorization');
res.json(
[
{id:1,username:"Awshaf"},
{id:2,username:"Fox"},
]
)
});
Nice, Thanks
wow great.... fastest and amezing tutorial
I'm getting a lot of errors through various set up steps because of Jade.. I installed pug and deleted jade from the package.json files, and again I'm getting Jade-related errors while trying to render the app on port 3001 : " Error: Cannot find module 'jade' "
I think the only other place 'jade' is referenced is in app.js -- make sure to change the line "app.set('view engine', 'jade')" to point to pug instead.
thank you so much
For anyone on windows, I would like to add that to start Express, the way you did it in the video did not work for me. I first set the port to 3001 using SET PORT=3001. Then, I used > set DEBUG=myapp:* & npm start to start Express.
Or you can use below code in app.js
var server= app.listen(3010,function(){
console.log('Listining on port number 3010');
};
How exactly do you overcome the "InvalidHost header" issue? I can't even live host to test & expand it .. >.
I think that’s to do with the proxy setting, and might also have something to do with if you’re running the server locally or remotely. Check out github.com/facebook/create-react-app/issues/2271
I'm getting the error "user is not defined" when running the react app, any help?
Probably a typo somewhere. That sounds like you’re accessing “user” somewhere but it’s not declared as a variable. Scope issue maybe?
for some reason I keep getting this error: "cannot find module 'http-errors' " when I try to run set PORT=3001 && node bin/www
Strange. You could try installing that I guess (npm install http-errors) but I wonder where it's coming from. Maybe try deleting node_modules and reinstalling from scratch - it could be that some packages got missed.
Thank-you I had missed a step it's working now, Love the video very helpful!
react's package.json "proxy": "localhost:8080" parsing error... help me
That looks good - look for missing comma's though, like on the line before it...
can you do tutorial to implement csurf in CRA and express
What chrome extension is that on your new tab page?
It's called Palettab - palettab.com/ - it shows a random set of 5 colors and fonts for every new tab you open.
Khalsa Ji
I would like to request to make more tutorials videos
just spent over an hour trying to fix an error, the proxy wasn't working for me....and then the solution was to delete package-lock.json and node modules and do npm install again. Feeling a little salty lol.
Thank you for the brief but clear video though!
short simple sweet
Hi Dave,
Your video is awesome and very understandable. I just copied the same way you have explained and got following error:
Access to fetch at 'localhost:3000/users' from origin 'localhost:3002' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I'm on Windows machine.
Now how do I setup graphql with it?
3:24 is that an emulator?
nvm I was thinking in react native..
where can i read about it?
Wooww.. Great Video.. But a little issue. My proxy isn't working.
legend.
I got the error:
Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
7 |
8 | componentDidMount() {
9 | fetch('/users')
> 10 | .then(res => res.json())
11 | .then(users => this.setState({ users }))
12 | }
13 | render() {
That usually means that the server returned HTML instead of JSON. Since the HTML starts with "
For those having the same error:
componentDidMount() {
fetch(`./users`, {
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(res => res.json())
.then(users => this.setState({ users }));
}
If it still doesn't work :
rm -rf node_modules
npm i
npm start
It worked for me
But doesnt create-react-app already create you a server
CJ B Sort of. The CRA server is only for development, and it only builds & serves the React app. It doesn’t & can’t serve data, work with a DB, etc. It’s not a back end server. For that you need something like Express, Ruby on Rails, etc - a server meant to do backend work.
thanks soooo much man.
does anyone knows how to connect express to mongodb ?
How to deploy to Digital Ocean?
thank you
Thanks a lot!
But how do you submit a post request to your server through the React App
I haven't tried this out myself, but my guess is that since you have that proxy set up in your package.json, you can perform any CRUD operation. So, just do a post request using 'fetch', and catch it in your server with 'app.post'. Again, this may or may not work as I haven't tried it myself.
what about post ?
hello so i can use it without installing mongodb
Yes, there's no database involved here. You can follow this tutorial without having mongodb or any other database installed. Of course, if you want to make a real app and store some data, you will need to revisit this ;)
so i don't need mongodb to store data or fetch data from the front end?
The short answer is: if you want to save data, install mongodb. The longer answer: If you just want a simple backend to handle front-end requests, and keep the data in memory, you can get by without a database like MongoDB. That'll be ok to just get something going (but the data will disappear when the server quits). If you want to be able to actually save users' data, you'll need a database, and MongoDB is a solid choice (not the only choice, but it's a popular one to use with Node).
how can i setup mongodb and fetch data, do you have a tutorial for it?
proxy 5000 line not working , showing just 3000
Totally upset, there are a lot of beginners out here want to learn , that’s will nice if slow down little also throw some details
Thanks 🙏
Thanks
Thank you for providing this content - very helpful! I have been trying to figure out how to do a GET query by id perhaps. Would you be able to provide a resource?
All those who make 50 hours tutorial videos for the same thing have a special place reserved in hell.