Route file failing to update in Express.js - javascript

I am new to using both Node and Express.
Express.js looked great, so I created a local deployment of a vanilla install.
Visiting http://localhost:3000/users prints the expected message:
respond with a resource
I try changing the text to this instead:
respond with no resource
But the change is not made. This is the contents of users.js, almost exactly the same as default:
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with no resource');
});
module.exports = router;
And here is a screenshot. Top left is the above code. Bottom left demonstrates a grep for "respond with a resource" failing to produce any results. The right hand side is my browser displaying old data.
What am I doing wrong that the data is not updating?

Your application will not automatically update if you use node <path/to/main>.js to run your application. node will run your application in the form it was when initially started, until that process is terminated.
The most common way to address this is by using a process manager, the most popular one used during development is nodemon. To use nodemon, install it globally on your machine using npm i -g nodemon (you'll probably need admin rights to do this). Then, run your application using nodemon instead of node.
nodemon <path/to/main>.js

Related

Rendering react with node.js in development

I am (very) new to node.js and I am trying to get a development environment started with React.
const express = require('express')
const mongoose = require('mongoose')
const app = express()
// this displays the index.html file
app.use(express.static(__dirname + '/public'));
// trying to see the app.js
app.get('/', (req, res) => {
res.render('app')
})
app.listen(process.env.PORT || 5000);
Right now I am simply trying to be able to view my app.js when I run nodemon. But right now it is only showing the index.html file in the public folder. and when I run npm start it renders both the index.html and the app.js.
I am 100% doing something wrong and am not in my element here. Any help/advice would be appreciated.
My full repo is here for viewing here
Thank you in advance.
Your code is simply serving a static HTML file located in the public directory everytime the user make a GET request to the root (in your case, localhost:5000). It is not interacting with React yet.
Usually when starting a project with React (frontend) and Node (backend), you would create them as separate projects, in separate repositories.
So you could create a React application using a bootstrap such as create-react-app running on PORT 3000 and in another terminal tab, start your NodeJS application in PORT 5000 like in your example. Then, you can call your backend endpoint from your frontend React application, by referencing http://localhost:5000
By doing this, your backend code don't need to serve static files anymore, it can return data such as JSON and make connections to a database for example.
Since your question is not specific enough, you could be talking about server side render. In server side render apps using Node and React, you have a frontend built with React and a Node server that will return the same React code as a string, using the react-dom/server package to help. This is more complex, but basically you will have the same React code on the client AND on the server. There are performance benefits, because the user can see some content rendered right when he enters the page, without having to wait the React bundle (javascript file) to load. If you want to know more about creating a server side render app with React and Node, there is a nice digital ocean tutorial here
If you want to connect your react js project to the node js
In Development
you simply run their server and start it
In Production
You can use sendFile function coming from express.js to run the frontend
https://dev.to/loujaybee/using-create-react-app-with-express

'serve' is not recognized as an internal or external command to run react app

serve has been installed globally using npm install -g serve command and It works locally, but deploying to a Windows server gives the following error:
"serve" is not recognized as an internal or external command
How to fix this error? Also, what is the use of the server.js file in a react project, and how does it help with deployment?
npm serve is installed globally please click here to see the image
I know that running npx serve -s build should work. I had the same problem as you. The npx command works for me. If you have npx problems, check your version of nodejs. I'm running 10.16.2 (so that we're on the same page). https://www.npmjs.com/package/serve
The rest of your question is relative to the rest of your set up. I don't have a server.js file of my own (there are some node_module server.js files, is that what you mean)?
As I understand a create-react-app, npm run start will allow you to run your application locally. I don't need serve -s build for that.
I used an amplify create react app. For an amplify application, I just run amplify publish and my application's build directory is sent to an S3 bucket for me. If you don't have that configuration, and you want the quick and dirty answer... just take the contents of your build directory in your react application and drop those files on your web server. That should get you 90% of the way there (mind the default page that renders).
Serving React Files
Basic Exapmle:-
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);
For your base path in the domain serve the index.html you fetched from your build process.
If you need more info :- https://create-react-app.dev/docs/deployment

create-react-app shows an error of "You need to enable JavaScript to run this app."

I use express for my API. I have a folder named app and another folder named server. app is the client app, using create-react-app as boilerplate, while server is express.js app for the API.
in the app.js file of the server, I wrote
app.get("*", function (req, res) {
res.sendFile(path.resolve(__dirname, '../app/build/index.html'));
})
But then when I call any API endpoint, I get
You need to enable JavaScript to run this app.
in the response. I'm confused; what's wrong?
In the build directory you have more files that just index.html. You also have build/js/main.buildNumber.js and build/css/main.buildNumber.css.
So when your frontend makes a request to https://yourdomain.com/css/main.buildNumber.js, it incorrectly returns index.html not main.js.
Instead, you should serve the contents of the build folder statically with express.static
app.use('/', express.static(__dirname + '/'));
Or you can look into the "serve" node module to host your app. This will work nicely with react-router. npm i -g serve then cd build then serve . --single -p 5000. This will serve your app on port 5000 (http://localhost:5000).
For me, the issue was that I was mixing styles for functional and class based components. Double check that you don't have any dangling this keywords, or perhaps some missing of the same.

Getting an express app working online

I am new to expressjs and am trying to get my express application (done with the express generator) working on my website, I currently uploaded the directory which is is contained in like so..
http://www.example.com/express-app-here
so I could see it working online. However, when I navigate to where the App is, I seem to only get the directory structure, and express isn't routing me to the appropriate place like it is when I go to localhost:3000.
I take it this has something to do with the fact that express isn't executing my application? Locally,
npm start
needs to be run on the console in order to get it to run, is there some kind of log I need to execute this command in? Or something I need to change in the app.js or /bin directory?
As it was said in the comments, you need to have nodejs installed on your server. It's not as simple as just copying the node app directory over to the server.
You will have to install node and npm on the server, and then run your app from the server, probably using npm start like you were doing on your local machine.
From there, you will want to go into your app code and make sure a route exists for /express-app-here unless you want www.example.com:3000 to take you directly to the express app.
Basically do it like this:`
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var port = process.env.PORT || config.webServer.port || 3000;
server.listen(port, function () {
console.log('server running');
console.log(port);
console.log(server);
});
exports.module = exports = app;
save it app.js
Go to path via cmd. Now run:-
1)npm install express
2)npm install http
3)node app.js
Will be enough to run express server

Express + socket.io: socket.io client script is 404

This is driving me crazy... while I have a working version of Express + Socket.io, I can't seem to reproduce it with out-of-the-box NPM installs in a new project folder. Can anyone point out what I'm missing...? Here's my process:
I create a node_modules folder in my project directory (pwd), then do:
npm install express
npm install socket.io
Running those two commands puts the packages in my project's node_modules folder as expected. Now I set up my server with the following:
var express = require('express'),
server = express.createServer().use( express.static(__dirname+'./public') ).listen( 8080 ),
io = require('socket.io').listen(server);
My public folder contains static assets for my application. My public index HTML page includes a script tag for:
<script src="/socket.io/socket.io.js"></script>
Finally, I run my server script and go to the application in a web browser. My static public files are all served properly, however I get a 404 for /socket.io/socket.io.js. Now, I can swap in an express package from another old project and have this whole system work. Somehow that package instance is configured differently, but I can't figure out how to reproduce that. The Express website mentions something about installing dependencies, although running npm install -d doesn't seem to help (is there a specific pwd that I need to be in while running npm install -d?). I figure I must be missing something important about configuring a new Express instance after installing it with NPM.
Thanks for any and all insight!
Okay, so my example was actually an abbreviation of my code, and that example code does actually work. My real code with problems was a bit more cluttered, like so:
var server = express.createServer();
server
.use( server.router )
.use( express.static(__dirname+'/../public') )
.get('/api', function(req, res) {
res.write('API');
});
server.listen(8080);
var io = require('socket.io').listen(server);
I fixed the above code by doing the following:
server = server.listen(8080);
Apparently the listen command wraps the server object with some additional functionality. My originally posted shorthand example actually does work because listen is chained onto the final return into the server variable. Interesting little nuance.

Categories