Whenever I have to create a new project, I prefer to keep my stack with only one language. So I love use javascript for everything, with Node.js, E...
For further actions, you may consider blocking this person and/or reporting abuse
Hi Thiago, Thank you so much for this great tutorial. I followed the whole tutorial exactly as you mentioned and at the end when inserting the post requests to include some products... the console was showing this message:
GET localhost:3000/api/product 404 (Not Found)
dispatchXhrRequest @ xhr.js:178 ........
and then I changed in productService.js, axios.get("/api/product) for axios.get(
http://localhost:5000/api/product
) and the whole app worked!I have the proxy in the package.json included and everything...but not sure if I missed something..do you know why this happens?Thank you in advance!!!
Another thing, you should not include the localhost in your axios.get function call.
It should be axios.get("/api/product", ...).
The base URL definition is already set at the beginning of the application when we build the server and define a port, in this case 5000.
Hi Oscar,
Are you getting this error in the front-end console or is it in an HTTP client?
If this is in your react app, it seems like something is wrong with the proxy config.
It was showing this error inside Chrome Devtools (where localhost:3000).
Are you able to insert data through an HTTP client like Insomnia or postman?
I think I found the issue. I had included the sentence "proxy": "localhost:5000" inside the package.json belonging to the server, and not inside the package.json of the client(react app). May be that one the problem Thiago? Because now I´m not getting any errors.
That was it, for sure Oscar.
Let me know if you have any other questions! :)
Hi Thiago, This is a best useful and easily guide for beginner like me but I am facing a some problem...
Last year I have done it finished once and it work completely in my macbook but now I do one more on VMware. Everything almost work but it stuck in front-end part.
My app can GET and POST to localhost:5000, data was completely send to database but now it never found "product" from database cause my localhost:3000 always show "No products found" and white blank page...
I think because of client side but I am not sure which code cause this. Could you please adviseme Thiago. Thanks you !
Hi Melonfrappe!
Can you check in your browser's console and network tab what are the errors you get while trying to fetch the data?
It smells like a proxy error maybe.
Hi Thiago, thanks for this tuto. i was fighting with the proxy, reading the comments section i realize that in your tuto you put the proxy in the server package.json and not in the package.json of the client, maybe you can fix that for the incoming readers. againg thank you for this amazing tutorial
Hi Daniel, you are totally right!
I am sorry I made you struggle with that, I just fixed it!
Thank you for letting me know that.
Thiago, this is great, thanks. I'm a newbie here and this is exactly what I was looking for as a fullstack setup. I've managed to incorporate this in my first "planner" app. Next step for me is to POST data to the DB through the front-end. Thanks again.
I am very happy to know that it helped you!
Let me know if you have any questions.
Just sharing
If you got these error messages below,
(node:48490) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:48490) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
Change the code something like this
mongoose.connect(
process.env.MONGOD_URL ||
mongodb://localhost:27017/fdaksjfafdsfasa
,{ useNewUrlParser: true, useUnifiedTopology: true },
(err) => {
if (err) console.error(err);
else console.log("Connected to the mongodb");
}
);
Hi Thiago! Great article.
I have one question. Once I send a post request for new products, and I look at the app, I just see bullets, but no product names or descriptions. Any idea why that might be?
Thanks!
Hey Tomrains, thank you! :)
If you can see the bullets in your view after creating products, this should probably be a problem in your view.
I recommend you put a console.log(product) inside the renderProduct arrow function, right in the beginning.
Let me know what you got there.
Hey Thiago, here's what I see in the console after I added in console.log(product) to the renderProduct arrow function:
thepracticaldev.s3.amazonaws.com/i...
Humm I see, actually the problem must be when you are creating the products.
What response do you get after making the post request to create a product?
You should get something like this:
{
"error": false,
"product": {
"id": "5dab7eb6fc634a193f1f05f6",
"name": "product 1",
"description": "description",
"_v": 0
}
}
Here's what I'm getting:
thepracticaldev.s3.amazonaws.com/i...
So for some reason the response doesn't have the info I put in?
Oh I see tomrains, you are sending a post request with a x-www-form-urlencoded, when you should actually be sending a json.
I think in postman you should select the option raw.
Give it a try and let me know if it worked! :)
It woooorked! Thanks so much Thiago. I'm having fun building my MERN app now :D
Greaaaat!! Very glad to help :D
Hi Thiago,
I have a similar problem to the one reported by @tomrains , but the answer you gave did not allow me to solve it.
(Note: I'm new to Postman)
the response I get for localhost:5000/api/product?name=to... is
{"error":false,"product":{"id":"5ee204bbf1af38409c11d4de","_v":0}}
the response code is 201 Created.
In the Pretty - Raw - Preview section, I can't edit, it's read only
I added a Content-type: raw section in the headers but that didn't change anything.
I tried using curl, with this command: curl --location --request POST "localhost:5000/api/product" --header "Content-Type: raw" -d '{"name":"toto","description":"tata"}'
but the result seems to be the same...
Here's a screenshot of my postman app:
dev-to-uploads.s3.amazonaws.com/i/...
Hi Francis.
In your screenshot, I can see that you are sending query params with the values when you should actually be sending body data in postman.
You can select the body option and you will have a raw option below it.
Follow a screenshot below with an example:
dev-to-uploads.s3.amazonaws.com/i/...
thank you so much, Thiago! That was really quick! It works now. It seems obvious once you know where to look.
When I try to run the app, I get an error like the one below :/ which is annoying as it's a dependency. Anyone know what to do about that?
TypeError: Cannot use 'in' operator to search for 'autoCreate' in true
at NativeConnection.Connection.openUri (/Users/vhu02/Documents/Apprentice_work/node-react-starter/node_modules/mongoose/lib/connection.js:561:22)
at Mongoose.connect (/Users/vhu02/Documents/Apprentice_work/node-react-starter/node_modules/mongoose/lib/index.js:332:15)
at Object. (/Users/vhu02/Documents/Apprentice_work/node-react-starter/index.js:11:10)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Function.Module.runMain (module.js:694:10)
at startup (bootstrap_node.js:204:16)
at bootstrap_node.js:625:3
[nodemon] app crashed - waiting for file changes before starting...
For the proxy issue follow the steps below.
Replace the ' const proxy' in setupProxy.js file with this.
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use('/api',
createProxyMiddleware({
target: 'localhost:5000',
changeOrigin: true
})
);
};
it works. You can follow . Please let me know here
Hey Veronika,
Could you share the code that reproduces this error, please?
There is nothing much to share as I just followed these steps haha
OMG really? haha
I just download the source code and tested it here. Everything works fine.
Could you try to clone the repo and test it just in case?
yeah so I forked your Github, and the proxy still isn't working. I seem to get a deprecation error
What you could try to do is to add the following line in your client/package.json file:
"proxy": "localhost:5000"
That should solve the problem.
I did try that as the other comment addressed it and it didn't seem to work.
the exact error I'm getting is this:
DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
events.js:183
throw er; // Unhandled 'error' event
Veronika,
Does the error persist once you modify the line:
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/node-react-starter',{ useNewUrlParser: true });
as suggested by the Deprecation Warning?
What is the prompt error if so?
This deprecation warning should not prevent you from running the app, but the rpacheco suggestion should do the trick.
You can also add this config on another line, like so:
mongoose.set("useNewUrlParser", true);
You might also find other deprecation warnings in the future, follow a list below in case you need it.
mongoose.set("useFindAndModify", false);
mongoose.set("useCreateIndex", true);
mongoose.set("useUnifiedTopology", true);
Let me know if that worked for you.
Hi! excellent post. i like this configuration and now i'm using it. But i have a problem, i don't know how configure script for debug in vscode. i was trying but with bad results. Could help me with this?
Hi Leo,
You can create a file launch.json inside the folder .vscode with the following code:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch via npm",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "npm",
"runtimeArgs": ["run-script", "dev"],
"port": 9229
},
]
}
Then you can just hit F5 and your app might run.
Let me know if that works for you! :)
Hi thiago, Thanks for response. i was make that how you tell me but pick a error ECONNREFUSED.
reason: Cannot connect to the target: connect ECONNREFUSED 127.0.0.1:9229.
the .vscode is the same that you give me, and the package.json is the same that the tutorial.
server for mongodb is up, but for the error my targe is wrong.
thi is my index.js
dev-to-uploads.s3.amazonaws.com/i/...
Hi Leo,
Sorry, You should also have a new debug script in your package.json file. Add the following script to your package.json:
"debug": "nodemon --nolazy --inspect-brk=9229 index.js",
Also, update the launch.json runtimeArgs to use this new script:
"runtimeArgs": ["run-script", "debug"],
Let me know if that works for you
Hi there,
so I found app.delete(
/api/product/:id
, async (req, res) => {const {id} = req.params;
let product = await Product.findByIdAndDelete(id);
return res.status(202).send({
error: false,
product
})
})
that I try to call from postman with:
localhost:5000/api/product/:id
With a raw body of JSON of:
{"name": "myName"}
but it sais:
Cannot DELETE /api/product/
Do you guys know what Im missing?
Thanks in advance!
Csaba
Hi Csaba,
By the error, it could be something wrong with the definition of this app.delete method.
Does your backend log any error in the terminal when you test this endpoint?
If everything is correct in your code, the error could be the ID you are passing in the URL.
As this is just a simple tutorial and I wanted it to be short, it does not have validations but, in a final application, it should contain a lot of validations on the data we are trying to execute actions.
My suggestion to you is to check if the ID you are passing to the URL
http://localhost:5000/api/product/<YOUR-PRODUCT-ID>
is a valid ID.Let me know if this helped you solve the problem and do not hesitate to ask if you have more questions.
This is a great article!
And a big thank you, for also showing the configuration for production/deployment.
I feel that it's often left out, and for a beginner in the web development field, this is key!
Keep up the good work!
Thank you, Jonas!
Let me know if you need any help :)
Thanks Thiago, nice tutorial. I notice your code doesn't have 'require('dotenv').config()' or the npm package install in the instructions??
Am I missing something, are you using some native way of reading the .env file, thanks!
Alan
Hi Alan, thank you.
I am not using a .env file here, I am only using the process.env variables, assuming that the additional custom variables would be defined on the server.
Thanks Thiago,
I think I see what happened, I'm connecting to a db on Mongo Atlas and copied a line of code from another project!! Thanks for looking, cheers.
Alan
Great guide, thank you!
Question, any idea why the proxy breaks when using a api url more than two levels deep? "/api/blocks" works whereas "/api/blocks/all" does not. Everything else is the same and api routes work separately.
Tried "/api" and "/api/**" in setupProxy.js to no avail.
Hi Alg, sorry for the delayed answer and thank you for your comment.
This deep routes should work as the other ones. What I recommend to you is to use the proxy config that react supports now.
You can simply put the following line in your package.json file:
"proxy": "localhost:5000"
This should do the trick.
Let me know if that works for you!
hi,
nice article and i almost followed the steps, but in my sample application I just want notification from node express so for that I used socket.io and socket.io-client so in test application if I set proxy in setupProxy like app.use(proxy('/', { target: 'localhost:5000' })) than its not working, but if i added "proxy": "localhost:5000" in package.json than its working.
i want to set proxy in setupProxy file.
Thanks
Hi there.
I recommend you to stick with the package.json proxy approach, now that it is supported in the latest version (I don't know exactly since when lol).
I will probably update that in the post as soon as I can.
Hi all!
First of all, thanks to @pacheco for the tutorial!
One thing I keep wondering, after seeing many full-stack mongoose tutorials, is why do we have to define the same data model and logic twice, one in the backend, and - at least partially - in the front-end?
Probably I am missing something, which I will find out when trying, but I am sure anybody must have bothered to try before, to re-use the back-end data model in the front-end? What happened to the idea of isomorphic apps after all?
I can imagine that either re-using the exact same JavaScript code for BE + FE data models would introduce technical debt, coupling or even unintended downsides concerning front-end business logic, or else it's just not compatible enough and the amount of redundancy does not seem to be critical and will be covered by unit tests + end to end testing, at least if there are tests at all?
Hope somebody will share their thoughts and experience...
Hello guy, thanks a lot for your content, i actually have a a project similar to that one and it helped. So my question is there any Dockerize version of this app available yet ?
Hello,
As we are all in this quarentine, I'm working right now on a tutorial for that. I will try to post it today. :)
I just made a post about how to dockerize this app and deploy a container to heroku.
dev.to/pacheco/how-to-dockerize-a-...
Check it out! :)
This is the Deploy logs when it is production ready (it works locally), what do you think the problem is ?
The proxy isn't working for me
Hello Rajat,
Can you tell me if testing the backend and frontend separately works correctly?
I just gave it another try here and everything works perfect.
Another option you could try is to config the proxy directly in the package.json, the latest versions of react supports this. It is as simple as adding the following line to your package.json file:
"proxy": "localhost:5000"
Adding proxy key worked. Thanks! 😃
Great Rajat!! :D
Very confusing documentation.
For example: dev-to-uploads.s3.amazonaws.com/i/...
Which package.json?
Hi Mustafa, how are you?
I am sorry if that was not that clear, it was my first article so I am still improving it.
But as I said in this part, it is the package.json located in the root of the project, which means the file related to the backend part.
Let me know if I can help you with anything else.
Sorry if I am being rude.
For example, in your doc, you says process.env.MONGODB_URI or process.env.NODE_ENV but all that give errors "undefined"
so what can I do?
Hi Mustafa,
These variables when working on the localhost will be undefined, but that should not trigger errors because there is a checking on each of them applying another value in case they are undefined.
These are the environment variables that can make the app production-ready. For example, the MONGODB_URI will be used as your production mongo URL and the NODE_ENV will be used to render the correct front-end application in case it is set to production.
They are used in the following tutorials (found at the end of the article) about how to dockerize and deploy this app.
Thanks for the reply. I have sent the message you via instagram dm. I need more explanations.
Anyway, you said in your doc:
"Now if we run the project we are able to make requests to our simple product api using the url localhost:5000/api/product.
Here we can get, insert, update and delete a product."
But I tried it with postman but it waits too long. nothing returns.
For instance:
localhost:5000/api/product?name=mu...
it says, "sending request..." and it stucks.
I am having an issue whenever I try to access the backend server in the browser it says server might be temporarily down.....Why is that....btw I exactly tried the code you mentioned above....
Hello there, can you confirm what errors do you get in the backend and frontend logs of your application?
What to do if we want to deploy multiple apps? They must share the same database, correct?
Hi Jack,
That depends on the project you are working on.
Currently, with almost everything migrating to microservices approach, it is common to have one database for each service/functionality.
Amazing. Works perfectly. Thx.
Small correction - productRoutes.js referenced as productRoute.js (singular) in this page.
Oh, true! Thank you very much for reporting that, I will fix it. :)
[0] [nodemon] app crashed - waiting for file changes before starting...
[1] proxy is not a function
It seems like you do not have the http-proxy-middleware package installed.