MERN Stack Tutorial #9 - Fetching Data
ฝัง
- เผยแพร่เมื่อ 10 ก.พ. 2025
- In this MERN stack tutorial we'll make a request to the backend api to fetch workouts data and output it in the React template.
⭐⭐ Get the full course now (without ads) on the Net Ninja Pro site:
netninja.dev/p...
⭐⭐ Get access to all free & PREMIUM courses on Net Ninja Pro:
net-ninja-pro....
🥷 Course Files (GitHub):
github.com/iam...
💻 Node.js & Express Crash Course:
On Net Ninja Pro - netninja.dev/p...
On TH-cam - • Node.js Crash Course T...
💻 MongoDB Crash Course:
On Net Ninja Pro - netninja.dev/p...
On TH-cam - • Complete MongoDB Tutor...
💻 React Full Courses:
On Net Ninja Pro - netninja.dev/p...
On Udemy - www.thenetninj...
On TH-cam - • Full React Tutorial #1...
🔥🔥🔥 Other resources:
React Context & Hooks tutorial (on TH-cam) - • React Context & Hooks ...
VS Code - code.visualstu...
MongoDB Atlas -www.mongodb.co...
POSTMAN - www.postman.co...
You are way better and the greatest professor. I am studying at a college in Canada. You explained it so well that my professor in my college could not even explain it well enough to understand in the last month. You just the whole thing in this short video.
That means a lot, thanks! :) glad it was helpful
I wasted three days on this part not getting my workouts title to show up. finally installed cors and everything was fine. If anybody is not able to fetch the data from the backend use proxy then try using cors. It helped for me hope it helps you too.
Please, can you paste the line of codes.
I'm having same issues now.
Cors not working. It doesn't allow connection to mongodb
@@kinglegitto1848 what have you used bro. I'm facing the same issue now with proxy
For those stuck...delete that proxy in the frontend and npm install cors and require it like this const cors= require('cors'). Then use it as the first middleware immediately after the middleware comment by just typing app.use(cors). Then don't forget to rewrite the fetch api in the Home.js .Remember he had removed the localhost:4000 when he used the proxy. Now just rewrite as the he had initially done and it will work fine.
Okay it works now. For some reason, using mobile hotspot from my phone to my laptop confuses mongodb while cors is active. Without cors, it connect but with cors and the hotspot from my phone, I get an internal error from mongo.
I set the mongo atlas to allow all ips and it seems to behave well now. Btw, when I'm connected to wifi both work together with no issues.
I’m doing a full stack react native app rn and this video is just what I needed! Thanks again!
Lovely I will be diving into react native real soon
Hi Nate Duncan, Can we do the project together?
Awesome series Shaun. I've almost covered everything related to MERN from your channel, only the JWT authentication is left. Now I badly want a series similar to this one on < (React + Redux or Next) + typescript + Firebase + tailwind > to upskill my frontend skill. I know you have separate courses on each of them, but a mix-up would make us help become production-level developers real soon!
Finally, been waiting all day for this😍😍.
I used Axios instead of the fetch api though
Hey man can you help me out. I'm trying with axios too but proxy doesn't seem to work
Hi lekan could you help me I also trying to connect my frontend with backend using axios but it doesn't work..
@@tusharadhikari1507 share your GitHub repo link
@@tusharadhikari1507 npm install axios // import axios from "axios" // axios.get("/api/workouts").then((response) => setWorkouts(response.data))
There's perhaps another layer of nesting before you get to the workouts array inside the json. Therefore, instead of
if (response.ok) {
setWorkouts(json);
}
do the following
if (response.ok) {
setWorkouts(json.workout);
}
in your frontend package.json file
"proxy": "localhost:4000/api/
in your useEffect do the following
const response = await fetch("workouts/");
There's perhaps another layer of nesting before you get to the workouts array inside the json. Therefore, instead of if (response.ok) {
setWorkouts(json);
}
Do this
There's perhaps another layer of nesting before you get to the workouts array inside the json. Therefore, instead of if (response.ok) {
setWorkouts(json.workout);
}
TO SUMMARIZE::
in your frontend package.json file
"proxy": "localhost:4000/api/
while in your Home component do the bellow
useEffect(() => {
const fetchWorkout = async () => {
const response = await fetch("workouts/");
const json = await response.json();
if (response.ok) {
setWorkouts(json.workout);
}
};
fetchWorkout();
}, []);
If his way of fixing the cors policy didn't work for you, just install the cors package in your backend folder with: "npm install cors", then, in the server.js file, import the cors package with "const cors = require("cors"), and then use it app.use(cors())
Thanks bro
1st time I understand what does proxy field inside package dot json file !!! awesome work
Glad it helped :)
@@NetNinja Proxy not working for me 😥
@@WEBDEVIndo same, you found a solution?
@@noOne-fe4niyou found a solution?
If you are still getting a proxy error make sure when you run "npm start" from your frontend folder, that the backend is running (npm run dev) at the same time. i.e. you should have two terminals running
thanks bro :)
Yessssssssss! Already waiting for the next series! 😁😁
I used vite instead of creaate-react-app for the front end. For whatever reason, the method shown in the video didn't work. I got it to work when I installed the cors package, then in server.js, I added at the top:
var cors = require("cors");
then, right after the express middleware, app.use(...), I added:
app.use(cors());
That worked for me anyway, hope it helps if you're running into any issues. 🤓
please hekp me out am also using vite
it worked thanks man
Awesome tut series
Can someine help me? I did everything in the video right but the workouts won't show up on my web page. I keep getting this error Unexpected token '
useEffect(()=>{
const fetchWorkouts= async ()=>{
const response = await fetch('localhost:4000/api/workouts');
//rest of code
I got the same error when I write await fetch('api/workouts'). I resolve the error when I write the whole link as per above. I use cors instead of proxy
@@aivkhairulamirin9004 Holy shit you solved my issue!! I was this close to giving up on even starting an app!
did u fix this
Just bought the course. A steal at $2.40..... Support your local Dojo ✊
Awesome, thanks for the support Jimmy!
Should we not have used a try/catch in the useEffect in case we were not able to parse the json? Is there not a risk of crash if something went wrong?
Yes, that's a good idea.
Just following this now. I was also unable to get the json to parse. What worked was installing cors, importing it in the server file, using it as middleware, getting rid of the proxy, then putting the full api path back into the home file
if you were a chick, I'd kiss you right now. Thanks for explaining it so easily! Saved my head from emitting too much smoke
finally someone said what needed to be said lmao. i forgot to turn the fetch url back to pre-proxy method.
It's a good challenge trying to understand the last lessons using Course Files :-)
If you have seen your video - you understand topics entirely, but if you just read code without a video you start to develop some new skills)
I'm getting this error "DeprecationWarning: The `util._extend` API is deprecated. Please use Object.assign() instead." but cant find the extend function used anywhere. Any ideas?
8:01 the proxy method to fetch the API didn't work for me.
I'm getting this error
Dev Server has been initialized using an options object that does not match the API schema.
- options.allowedHosts[0] should be a non-empty string.
Could someone help?
There's perhaps another layer of nesting before you get to the workouts array inside the json. Therefore, instead of
if (response.ok) {
setWorkouts(json);
}
do the following
if (response.ok) {
setWorkouts(json.workout);
}
in your frontend package.json file
"proxy": "localhost:4000/api/
in your useEffect do the following
const response = await fetch("workouts/");
There's perhaps another layer of nesting before you get to the workouts array inside the json. Therefore, instead of if (response.ok) {
setWorkouts(json);
}
Do this
There's perhaps another layer of nesting before you get to the workouts array inside the json. Therefore, instead of if (response.ok) {
setWorkouts(json.workout);
}
TO SUMMARIZE::
in your frontend package.json file
"proxy": "localhost:4000/api/
while in your Home component do the bellow
useEffect(() => {
const fetchWorkout = async () => {
const response = await fetch("workouts/");
const json = await response.json();
if (response.ok) {
setWorkouts(json.workout);
}
};
fetchWorkout();
}, []);
@@harunjib9480 Still getting the same error
@@umarbusy lemme see your error message.
Did you follow the solutions I provided?
@@harunjib9480 I did your steps, Im still getting an error. JSON.parse: unexpected character at line 1 column 1 of the JSON data
Bro have you solved this error
" Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 "
I got this error, can you please help me?
I got this error too. Just restart the npm start. This will work out
thanks 🤗
@@njw_cs That sollution wasnt helpme... Did you have success???
@@leodk16 you can change the port for the frontend part, to do so simply go to package.json file and change port from start script just as follow:
"start": "set PORT=3006 && react-scripts start",
There's perhaps another layer of nesting before you get to the workouts array inside the json. Therefore, instead of
if (response.ok) {
setWorkouts(json);
}
do the following
if (response.ok) {
setWorkouts(json.workout);
}
in your frontend package.json file
"proxy": "localhost:4000/api/
in your useEffect do the following
const response = await fetch("workouts/");
There's perhaps another layer of nesting before you get to the workouts array inside the json. Therefore, instead of if (response.ok) {
setWorkouts(json);
}
Do this
There's perhaps another layer of nesting before you get to the workouts array inside the json. Therefore, instead of if (response.ok) {
setWorkouts(json.workout);
}
TO SUMMARIZE::
in your frontend package.json file
"proxy": "localhost:4000/api/
while in your Home component do the bellow
useEffect(() => {
const fetchWorkout = async () => {
const response = await fetch("workouts/");
const json = await response.json();
if (response.ok) {
setWorkouts(json.workout);
}
};
fetchWorkout();
}, []);
finally i got this... thx god and thx net NINJA!!!! /// i really want fullstack developer and make fullstack project.. then you really big help for me . thank you very * 1000 much ♥
hey guys I need your help I keep getting this error
Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
- options.allowedHosts[0] should be a non-empty string
but when I remove the proxy from the package.json in the react it works just fine
ME TOO
in your package.json:
"options": {
"allowedHosts": ["localhost", ".localhost"],
"proxy": "localhost:8080/"
}
Youre the best ❤
Earned a follower 😅🎉
very sneaky with your css xD
what extension allows you to have special icons for your folder and such? also what extension do you use for the nav.pages to expand into a complete div with a class?
I am getting this error. Please help - JSON.parse: unexpected character at line 1 column 1 of the JSON data
same. Did you find the solution?
@@hersheynaik3029 So, the error happens when the server sends back something that's not valid JSON, like an HTML document. The fix was to install CORS on the server and set it up properly. That got the server to send back the right JSON responses, and the error went away.
Go to the backend folder in your terminal and install cors there. Then, you have to configure your server.js and import cors.
Which is your next udemy course Shaun eagerly waiting man, love you ❤️
i have a question, when i put the given index.css the box, color, and design doesn't show
yay 😍😍✌🏻👍🏻
Good day everyone,
I'm having trouble fetching data from the database (the 'getworkouts' request).
I'm sure following the code in thr tutorial lecture code line for code line but it somehow seems to not be working for me.
Getting an error in the console: "
Hello guys,
I have been able to fix the bug in my code. Below's a breakdown of how I went about it.
1st => Stop the back end server by pressing 'ctrl + C' ('ctrl' and the letter 'c' key on your keyboard') in the terminal where the backend server was being run.
2nd => Install the 'cors' package as a dependency on the backend by running terminal by entering this command in the terminal: 'npm I cors' and press the 'enter' key on the keyboard.
3rd => Next go to the 'server.js' file in the backend folder and enter the following code snippet:
require("dotenv").config();
// import cors
const cors = require("cors");
const express = require("express");
const workoutRoutes = require("./routes/workouts");
// express app
const app = express();
// use cors for the app
app.use(cors({ origin: "localhost:3000" }));
const mongoose = require("mongoose");
// middleware
app.use(express.json());
app.use((req, res, next) => {
console.log(req.path, req.method);
next();
});
// routes
app.use("/api/workouts", workoutRoutes);
// connect to db
mongoose
.connect(process.env.MONGO_URI)
.then(() => {
// listen for requests
app.listen(process.env.PORT, () => {
console.log("Connected to db & Listening on port 4000");
});
})
.catch((error) => {
console.log(error);
});
4th => remove the "proxy": "http:/localhost//4000" that you must have already added from following tutorial lecture video on lecture 9.
5th => Replace the codes in your 'Home.js' file/component with the below lines of code:
const Home = () => {
const [workouts, setWorkouts] = useState(null);
useEffect(() => {
const fetchWorkouts = async () => {
const response = await fetch("localhost:4000/api/workouts");
const json = await response.json();
if (response.ok) {
setWorkouts(json);
}
};
fetchWorkouts();
}, []);
return (
{workouts &&
workouts.map((workout) => {workout.title})}
);
};
export default Home;
6th => From here, everything should work fine.
I'd be open to help should anyone require any further assistance on fixing the error that arises from fetching the data from the 'Home.js' component
And please take not that the codes I've pasted as above are valid up till the 8:59 minute of the "Fetching Data" lecture of this course (Tutorial video 9 of this MERN STACK tutorial).
Thanks 🙏
@@augustine_edeh thank you bro it fixed my errors
this is really amazing
Hello. What extractions are you using for react snippets?
king of tutor
Master is there a way to run server and client on the same port. And all we have to do is to start the server and the server internally spins up the client for us and even hot reloads on any change in client.
You are life saver!!!!
If anyone is facing the error of the workout title NOT SHOWING UP, I added a return in the map function, which populated the workout title on my frontend
return (
{workouts &&
workouts.map((workout) => {
return {workout.title};
})}
);
};
Hope it helps.
workouts.map((workout)=>{ } ) without writing return statement will result in error.
use round bracket instead if we do not want to write return statement.
workouts.map((workout)=>( ) )
It'd be more exciting if u make react ssr
ti amiamo dall'italia
Hey there,
I'm stuck on your 9th video in the playlist because I keep running into a CORS error while trying to use a proxy. The error message keeps popping up saying: "Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. - options.allowedHosts[0] should be a non-empty string."
I'm a big fan from India, and I was wondering if you could help me out with this issue?
in your package.json:
"options": {
"allowedHosts": ["localhost", ".localhost"],
"proxy": "localhost:8080/"
}
Hello i got an error says "Proxy error: Could not proxy request /api/workouts from localhost:3000 to localhost:4000." i cannot apply proxy on my react app
hey how can I upload both backend and frontend folder on github in same repo ?
cd.. and git init
MAKE SURE YOU ARE NOT USING A RESERVED PORT AND IF YOU ARE HAVE PROBLEM TO FETCH DATA THEN USE "CORS" IN EXPRESS NOT PROXY WAY
After installing Cors, I got a new error
Home.jsx:22 Uncaught (in promise) ReferenceError: response is not defined
at fetchWorkouts
i have a error can any solve it. Uncaught TypeError: workouts.map is not a function
Hi Asharudheen Kp, I faced same issue today. I guess you have missed using await before response.json(). Please check this once. Hope it helps😊😊
There's perhaps another layer of nesting before you get to the workouts array inside the json. Therefore, instead of
if (response.ok) {
setWorkouts(json);
}
do the following
if (response.ok) {
setWorkouts(json.workout);
}
in your frontend package.json file
"proxy": "localhost:4000/api/
in your useEffect do the following
const response = await fetch("workouts/");
There's perhaps another layer of nesting before you get to the workouts array inside the json. Therefore, instead of if (response.ok) {
setWorkouts(json);
}
Do this
There's perhaps another layer of nesting before you get to the workouts array inside the json. Therefore, instead of if (response.ok) {
setWorkouts(json.workout);
}
TO SUMMARIZE::
in your frontend package.json file
"proxy": "localhost:4000/api/
while in your Home component do the bellow
useEffect(() => {
const fetchWorkout = async () => {
const response = await fetch("workouts/");
const json = await response.json();
if (response.ok) {
setWorkouts(json.workout);
}
};
fetchWorkout();
}, []);
Thnx @Santhosh Medarametla
@@santhoshmedarametla4558 LifeSaver, I faced same issue and find out that I forget to put () behind the response.json. Thanks!!
@@santhoshmedarametla4558 thanks it worked
Hey Shaun! When is your next video update? Been waiting for 2 days now😅
Hello all, I am not getting an error and I am not able to see the workouts displayed
could you please help me in this matter?
most probably cors error, check your browser console there it might be showing
if so just do 1 thing
got to your backend folder and install cors by the command "npm i cors"
afterwards in your server.js file (your main server file) user cors as a middleware
eg app.use(cors())
i have faced the same issue
i have accidently used
const WorkoutDetails = ( workout ) => {
instead of
const WorkoutDetails = ({ workout }) => {
if u are not facing any error and still not being able to show fetched data check the syntax carefully
HELLO, I'm getting this ERROR, PLEASE HELP ME
Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Im getting the same error, did you manage to get a fix? :C
@@RebelFinatic share your code so we can debug it
Awesome video ++++++++++++++++++ 🙂
thanks
Getting this error
Invalid options object. Dev Server has been initialized using object that does no match the API schema. - options.allowedHosts[0] should be a non-empty string.
Solved it ....by installing cors package in the backend
step 1: stop nodejs server and install cors package by writing "npm i cors".
Step 2: write these lines in the server.js file.
const cors = require("cors")
const corsOptions={
origin:"*",
credentials:true,
OptionSuccessStatus:200
}
@@umarbusy where do i use corsOptions variable?
can i learn full mern from this playlist?????
Also watch his other playlists of seperate technologies
@@hand-somepaws9285 mern stack complete within 3 month from your channel?
Love these. Wish I could give more than 1 like per video
Thanks for the support Ashley :)
I'm following along but using svelte instead
Hey shaun please help me i get this error 'Uncaught in promise unexpected token
hey have you solved this issue?
@@kimharoldpinanonang8463 Yes why?
I'm getting the same thing.
guys add React in the import above so you save your self from westing couples of houre
this video have so much new things and he didnt explain as detail like other video
thx
How would I fetch just one workout?
Getting this error - Uncaught (in promise) SyntaxError: Unexpected token '
have you solved this issue?
@@kimharoldpinanonang8463 yeah..just use the CORS npm package in your backend instead of using the proxy things for Cross Origin Error. It worked for me
Good day.
Have you solved the issue?
I cant use the proxy in package.json file, does anyone know how to fix that?
Solution found see replies
Same here man
OK so you can use axios and then use the full length url in the get method like localhost4000/api/workouts and it seems to work. Idk if it'll give issues later tho
@@Makeshitjusbecuz i found a solution , there was a.stackoverflow question thay explains whats up. In short this is probably a bug for security reasons , and workaround was to npm install a package that does the proxy stuff for you.
I got this error too. Just restart the npm start. This will work out
@@bekirs4240 no need to do that. Just restart the react app and will work out
I am not able to fetch data even after looking at all the answers mentioned in the comment section, is someone willing to look at my code???? If yes i will share the github repo. thanks in advance
Same problem
Good video, however wouldn't you consider to move frontend application into backend so it could serve that static react app?:) Cuz currently you are like running one more server for a frontend only which doesn't make sense
Hello I'm learning MERN from this playlist. Thank you I've learned so much.
ERROR: "Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0"
However, I'm getting this error when wanting to fetch the data I followed everything so I'm sure of the code but no data is showing on the screen and this error is showing instead in the console. I tried some solutions I found on the internet such as JSON.parse etc. but nothing is working
HELP ME PLEASE
some typing issues
Same here. Did you find solution?
@@x7x9x666 not really sadly
Did you move to a different place since the last video? Becase I had the same problem but realized that I set the current IP address at my apartment and then when I got this error, I was working at my parents place. So the problem was that my current IP address changed that is why I had this error. I just went on Mongo DB and changed the current address now everything works fine. Hope it helps.
@Ryu Well. I solved it. Kinda...
For some reason proxy doesnt work for me.
So I just install cors in my express app.
Getting an error similar to others below: Uncaught (in promise) SyntaxError: Unexpected token '
had the same problem, this solution helped
I used cors instead of proxy
in the backend folder;
install cors
npm install cors
in server.js;
const cors = require('cors')
add middleware
app.use(cors())
@@kwameotengdarko2779 the app.use(cors()) worked for me just if I use it before the other middlewares, I mean after const app = express()
@@kwameotengdarko2779 this worked wonders, thanks!
@@kwameotengdarko2779 Thanks man it worked
@@kwameotengdarko2779 This worked perfectly, you are awesome!
I'm having problems with CORS... Can anyone help me? How do I disable this?
install CORS package or follow the proxy method given it the video , it works (check your port numbers and do not follow the port numbers from video)
I solved installing cors, after
server.js:
const cors = require('cors')
app.use(cors());
ready, can works without proxy
There's perhaps another layer of nesting before you get to the workouts array inside the json. Therefore, instead of
if (response.ok) {
setWorkouts(json);
}
do the following
if (response.ok) {
setWorkouts(json.workout);
}
in your frontend package.json file
"proxy": "localhost:4000/api/
in your useEffect do the following
const response = await fetch("workouts/");
There's perhaps another layer of nesting before you get to the workouts array inside the json. Therefore, instead of if (response.ok) {
setWorkouts(json);
}
Do this
There's perhaps another layer of nesting before you get to the workouts array inside the json. Therefore, instead of if (response.ok) {
setWorkouts(json.workout);
}
TO SUMMARIZE::
in your frontend package.json file
"proxy": "localhost:4000/api/
while in your Home component do the bellow
useEffect(() => {
const fetchWorkout = async () => {
const response = await fetch("workouts/");
const json = await response.json();
if (response.ok) {
setWorkouts(json.workout);
}
};
fetchWorkout();
}, []);
@@Josehernandezl thank you bro
9:49
instead of getting datra from backend I am getting this , Error: Unexpected token '
hey i am getting the same problem.Did you solve it?
Were you guys able to solve it?
@@Germane_5 proxy doesn't work for me so I used cors
@@ravhundal I did but don't remember at all, maybe just keep giving the data to chat got and let it debug it
I have the same problem. Were you guys able to solve it?
11:26 sus
Proxy issue:
Use 2 terminal, issue will be solved
I just get workout.map is not a function
setWorkouts(json.workouts); // fixes it
thanx for this tutorial but i would like to say something u speak very fast .There are people whose 1st language is not english
Hey, thanks for your comment. You can toggle the 'playback speed' on TH-cam, so it's a little slower :) hope that helps
{2023-02-21}
Everything is working fine, except when I start up my frontend I get this error - Proxy error: Could not proxy request /api/workouts from localhost:3000 to localhost:4000/. Tried looking possible solutions but I haven't had any luck so far. Any ideas as to why this error keeps popping up and how I might be able to fix it? Thanks!
Just had a similar issue
The fix for me: change your proxy address from https -> http
"proxy": "localhost:4000"
My theory: the 's' in 'https' stands for secure, so it's not allowing you to make the request to the server
@@chitts6027 Yep that seemed to do the trick. Thank you!
If anyone keeps getting an error after adding the proxy: ""localhost:4000"" to package.json file try running npm audit fix --force in your react terminal
guys dont do this it will crash your whole application, this guy doesnt no anything