Serving create-react-app build files on express server - javascript

I want to serve build files of my react app on my other express application. So I copied all the static files inside build folder to public folder inside my express application and I used.
app.use(express.static(path.join(__dirname, './public')));
app.get("/",(req,res)=>{
res.send()}
)
app.get("/differentRoute",(req,res)=>{
res.send()}
)
app.listen(4000)
When I make a get request on http://localhost:4000/ my react page loads perfectly, however when I make the same request on http://localhost:4000/differentRoute, nothing loads, can someone explain me how it works?

When you request / it finds the index.html file in the public directory, and serves it up using the static handler.
Nothing get ever get to the explicit handler for / since the static route always catches it first.
When you request /differentRoute, there is no matching file in the public directory so the explicit route for that is triggered. You call res.send() with no arguments, which doesn't make sense.
If you want to have URL based routing and don't want to use server side rendering, then use the HashRouter.
If you want to have real paths for the different pages in the app, then use server side rendering (e.g. with Next.js.

Related

React app not loading js file when accessing it with a non home page url

I have a react app which I serve with nodejs backend. My requirement is to inject a variable from node server to react code when it is running. When I access the app with the home page URL it works fine but not with other URLs. I am going to put more details to understand the complete scenario.
In node server I have code to create a file like this: dist folder is where react build is stored
fs.writeFileSync(
path.join(__dirname, "../dist", "config.js"),
`window.INJECTED_VARIABLE= { value: "qwerty", }`
);
In public > index.html I have this script to load the created config.js file.
<script src="./config.js"></script>
Now, when I run my node server and access my app with the home URL http://localhost:3000, I am able to access the injected value - window.INJECTED_VARIABLE as { value: "qwerty", } and config file is also present under "sources" tab in chrome devtools.
I have one page in my app - http://localhost:3000/profile/profileId, when I directly open my app with this URL, I see window.INJECTED_VARIABLE as undefined. It looks like there is no config file in source tab if we look in chrome devtools.
I am getting a same problem in production too.
Can anyone explain this behavior and help me in fixing it. I would appreciate any help.
The dot in ./config.js denotes a URL relative to the current path. i.e. A document served from /profile/profileId will request the file /profile/profileId/config.js - which doesn't exist.
To specify that a partial URL always be from the root, you should omit the dot.
<script src="/config.js"></script>

Node.js source code getting sent over to client

I'm building with Node.js locally and I came along a weird problem where if I typed localhost:8080/server.js, the whole server-side source code shows up in the browser (the server file's name is server.js). I guess what's happening is the server looks for server.js, finds itself in the directory and sends it over. That's a huge security risk right? Any way to solve it?
All my code files are present in the same folder; would changing that be the best way to fix the problem?
Since index.html and server.js are in the same folder then the server will send server.js when requested because it thinks it's javascript code for the client and not the server.
You should put the files you want to serve in sub folder (usually named public) like this:
public/index.html
public/style.css
then start the server using that folder with:
app.use(express.static("public"))

Getting web application production ready (angularjs/nodejs)

My web application consists of angularjs on front end side and nodejs server listening to client requests. This is my folder structure:Folder Structure
UX contains client side code and IT contains server side code. I am using gulp to watch over development changes and for packaging (you can see the dist folder in UX). I use two terminals to launch this web application locally. From one terminal, I use gulp serve (UX folder) to start a static UI server which monitors the changes as I make to UI and reflect back the changes on the browser immediately. From the second terminal, I start a node server2.js server.
The UX/src/app folder has a config file where I specify server ip address and app.js uses this info to connect to server (currently).
Now, I want to deploy this app over cloud. On the cloud, I have to specify a node it/server2.js as a starting point in its config file. Hence, I want the corresponding web link should point to index.html in UX/src/app folder.
Hence, I need some advice on how to integrate my client side app.js file in the server2.js file on server side.
I am an amateur.
Thanks a lot!
I added this code to my server2.js file:
var express = require("express");
var app = express();
app.use(express.static("ux/dist/"));
app.get("/", function(req, res, next){
res.sendFile('index.html');
});
Currently, it is invoking index.html page from UX folder. But, I am not sure whether I have done it the ideal way. Need help on this.

Setting up static assets paths, routing endpoints with koa and various middleares

Question:
How can I set up my static files so that both directories are visible to my index.html.
How can I send my index.html when you hit the default route using koa-router vs. just a .json file when I make an AJAX Get request?
Requirements:
I need static directories to be visible in my apps src/index.html
node_modules needs to be open for js libs.
src/assets needs to be open for images.
I need a router for 2 purposes :
1) serving up the initial index.html
2) CRUD endpoints to my DB.
Notes: I'm totally willing to add/subtract any middleware. But I would rather not change how I organize my directories.
Directory Structure:
Middleware:
koa-static // cant serve node_modules + src directory.
koa-send // can send static files but then breaks koa-static
koa-router // cannot
app.js
var serve = require('koa-static');
var send = require('koa-send');
var router = require('koa-router')();
var koa = require('koa');
var app = koa();
// need this for client side packages.
app.use(serve('./node_modules/'));
// need this for client side images, video, audio etc.
app.use(serve('./src/assets/'));
// Will serve up the inital html until html5 routing takes over.
router.get('/', function *(next) {
// send up src/index.html
});
// will serve json open a socket
router.get('/people', function *(next) {
// send the people.json file
});
app.use(router.routes()).use(router.allowedMethods());
// errors
app.on('error', function(err, ctx){
log.error('server error', err, ctx);
});
app.listen(3000);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Morningharwood</title>
</head>
<body>
<h1>suchwow</h1>
<img src="./assets/image1.png" alt="butts"> <!-- will 404 with routing -->
<script src="./node_modules/gun/gun.js"></script> <!-- will always 404 -->
<script>
var gun = Gun(options);
console.log(gun);
</script>
</body>
</html>
Well. it happens that I'm developing a similar kind of app
There's no problem on using koa-static to serve you static content and koa-router for you api endpoint. I never used koa-send directly. but I think you doesn't need too, given your set up
The only thing that matters is the order when attaching middleware to koa app. Try to attach koa-static first for your assets ( and maybe even index.html) and later use the koa-router for your api. Requests trying to get some static file never reach the router. and this way the router only responsibility will be serving your api
If that's not posible ( for example, because you have a bunch of non-static html files to server, consider taht you can have more than one router per app, even nesting one inside the other
( If the answer is not enough, give some time to cook a simple example. I'll post it as soon as possible)
EDIT: added a quick and dirty example here. Probably it doesn't work out of the box, but it's enough to get the idea

Basic Locally Hosted Web-server Functionality

I am working on an addition to a project to create dynamic HTML reports from data that is stored in a SQLite database. Initially, I tried to do everything client-side using things like browserify and sql.js, but I ran into a lot of issues trying to read from the .db file locally.
For that reason, I have now decided to spin up a very basic web server that will be locally hosted. Essentially, I want the user to be able to navigate to http://localhost:3000 and hit a landing page which is the home page of the report.
I have set up a very basic HTTP server using express with the following code running in node:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(process.env.PORT || 3000);
This works fine, and exposes the /public directory on port 3000, which has a placeholder index.html as of right now. My problem is, that when I try to start adding my code that reads from the SQLite database, none of the necessary require() functions work (specifically, require('fs'), due to it not being defined.
At a basic level, my question boils down to this:
How can i have the ability to read from the SQLite database file in the HTML/Javascript pages that live on the webserver? Whenever I try to use the necessary functions, it tells me that require() is not defined, or other similar errors.
Any help would be appreciated.

Categories

Resources