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
Related
I'm wondering how to run some server side JS which then starts a react app. Or if there is a way to explicitly segment sever vs client side JS, or do I have to just add and use Express to the react app?
Essentially I want to
node somefile.js
//do some server js stuff, then
npm run start
For example, if I wanted to check a users authentication status from a separate Next app before starting and serving a Docusaurus app.
In my application i have the client in one folder and the server in another. I successfully deployed the application to azure web apps, this can be found at: https://wulfdevpage.azurewebsites.net/ However, it takes nearly 15 seconds for the page to respond and render the client, (this is just the basic react-app client for now, but ill build this out further soon.) my problem is simply that it takes way to long for the server to respond with the application.
here is my folder structure
--client
- build
// - (other parts of the react app)
--server
- [other folders, like controllers, models etc.]
- server.js //entry point
in my server.js file this is how the build folder is served up.
// Set static folder
const __dirname = path.resolve();
app.use(express.static(path.join(__dirname, "public")));
if (process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname, "/client/build")));
app.get("*", (req, res) =>
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"))
);
} else {
app.get("/", (req, res) => {
res.send("API is running...");
});
}
This works, but again, it's taking nearly 15 seconds from the initial request to the client reaching my computer to make this work. I know a simple solution would be to just move the client to something like azure static web apps but I really don't want to go this route, I'd rather keep them all in one place for convenience's sake. There simply must be a quicker way to serve up the client.
The major cause of performance of initial load issue is adding too many components into a single bundle file, so it takes more time to loading of that bundle files. To avoid this kind of issue, we need to structure our components in an optimized way.
To solve this react itself has a native solution, which is code-splitting and lazy loading. Which allows splitting bundle files into a smaller size. Refer here
The performance issue fix with some configuration changes. If you haven't done this already, please check below once
Enable HTTP/2
HTTP/2 brings major changes to our favorite web protocol, and many of the changes aim to improve performance and reduce latency on the web
Turn Off the Application Request Routing Cookie
Turn off the routing cookie in the Configuration blade to improve performance and resiliency.
Keep the App Service Always On
To prevent the idle shutdown, you can set the Always On flag in the App Service Configuration blade.
Use local cache
In App Setting create the app with a key of WEBSITE_LOCAL_CACHE_OPTION and a value of Always. You'll then have a d:\home folder pointing to a local cache on the machine and populated with a copy of your site content.
Use App Service diagnostic to fetch more details on the issue
Refer here for more info
I head to create Nuxt SPA with routing and mb API in future like that:
Backend server (on express or smth else) listen and on request give entire SPA to client.
Now user can use everything on client side (include routing) with no more else requests to backend (mb API requests only)
It means that server should give some .html file with js and css files as SPA and it will work on client side.
I tried to run some commands like nuxt build and nuxt generate
It looks like they return a same result - js files couldn't be found
And index.html file doesn't work properly
After some researching I found a solution
But now I got this:
It can't open the fourth js file in another js file. Path isn't right!
Every time I tried to run it as a static html file and from localhost (and also with using Live Server)
I think I did a lot of crutches and there should be another built-in function or feature that allows us to do what I want
I wrote a lot - if I made a mistake or you didn't get smth - please, ask! I need any help
To test your locally built application, you need to serve all files within the generated /dist folder. You can setup very easily a local web server using Express/Node.js as you already have Node.js installed when running Nuxt. Create a new folder and install express via npm (run npm install express).
Then, copy everything from /dist into /public and create a file server.js:
const express = require('express');
const app = express();
app.use(express.static(__dirname + '/public'));
app.listen(3000);
Run the web server with node server.js and you can access your generated files on http://localhost:3000.
I have a web app. Back end with node and front end with React. Setup (simplified) goes like this:
index.js (the server)
client
package.json
The client
Now, the client folder contains a front end web application, its contents are basically same as what you get when you type create-react-app.
Inside client there is a build folder which I created by running npm run build from within the client folder.
Server
Now, the index.js from my main folder acts as the node server, inside it I have a line like:
app.use(express.static(__dirname + "/client/build"));
Using this approach I have merged my node server and a client front end application (located inside client folder). You can see I told the server to serve files from the client/build.
All was working fine, till I encountered this.
If I click a react button in my client app which manually calls my router using say:
this.props.router.push('/listmovies');
it correctly shows the page.
But if I type same page in URL address bar and hit ENTER I get error:
Cannot GET /listmovies
The latter error I am pretty sure comes from node server. Because there is no listener for listmovies in index.js (and there should not be). You see basically I think node is intercepting the call and giving me an error. Whereas in my former case where I called router.push I get a correct page.
I hope I managed to explain my problem. Can someone help how to solve this issue?
You have to make the express application redirect all requests to the main React file so react-router can take over. Something like this below the app.use.
app.get('*', function(req, res) {
res.sendFile(__dirname + '/client/build/index.html')
})
This basically handles all wildcards and points it to the index.html. Mind you if you are also implementing API routes on the express app have them above this wildcard statement because otherwise it will intercept them and treat them as client side react-router routes instead of server-side API routes.
Learning nodejs and started to created my own restful API using restify.
I have created a very simple server.js file which contains basically a hello world type example starting up like:
server.post('/api/messages', servicemanager.verifyFramework(), servicemanager.listen());
server.get(/.*/, restify.serveStatic({
'directory': '.',
'default': 'index.html'
}));
server.listen(process.env.port || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
which works fine locally. I cant hit http://localhost:3978 and I can test my API calls just fine calling http://localhost:3978/api/messages.
I have deployed my code into bitbucket and now I want to host these APIs in Azure using App Services.
My project structure is like so:
/topfolder
-/myproject
-/node_modules
-/node_modules...
server.js
package.json
index.html
When I setup the new app service in Azure, I can see that the deployment receives the code from BB, but the service never responds to my requests.
I have setup the home path of the app to live in: /site/wwwroot/topfolder/myproject and I can see the index.html when I navigate to http://myproject.azurewebsites.net so thats good.
I actually get a 404 error:
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
There are heaps of examples of how to setup continuous deployment using bitbucket and for the most part, they all seem to work, but my server.js file doesnt seem to be the getting called or starting up.
How can I debug whats going on here?
Is the packages.json file used in this scenario by Azure?
Thanks.
As the root directory path of the application hosted on Azure App Services, is D:\home\site\wwwroot. And about the nodejs application, the Azure fabric will find the entrance script in root directory like server.js. And the requests are handled via web.config in root directory. If there is missing server.js or web,config file, you will occur 404 error.
You can try to modify or your application's structure, like to:
-/node_modules
-/node_modules...
server.js
package.json
index.html
Then, you deploy your application to Azure via GIT or from BB, the Azure deployment task will run command npm install and generate the web.config wile in the root directory.
Any further concern, please feel free to let me know.