How to pass data from Node.JS to React build - node.js

Suppose this is my server.js:
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);
And this is the React component which is going to received the data from the server.js:
import * as React from 'react';
export const DisplayName = (props: any) = {
return (
<p>Hi there: {props.match.params.data}</p>
)
};
So how do I pass/post the data to this component from Server.js via URL: i.e. http://example.com/displayName/Phil, http://example.com/displayName/Jake...
Is it possible to do something like these?
app.get('/displayName/:data', function(req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
// or
app.post('/displayName/:data', function(req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

Related

Node.js: res.redirect function is not working

res.redirect function is used to redirect the user to another page by clicking a button. But the function's not working. Please find the code below.
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});
app.post("/failure", function (req, res) {
res.redirect("/");
});
app.post("/success", function(req, res) {
res.redirect("/");
});
app.listen(process.env.PORT || 3000, function () {
console.log("The server is running at port 3000");
});
Try moving
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});
below your other routes and try calling again
Try changing app.post to app.get:
app.get("/success", function(req, res) {
res.redirect("/");
});

Deployment of react app with express server gives blank screen but the app works fine with serve -s build

I am running the express server on localhost:8080. The API is working fine.
I have added a new folder called public in express server source and added the react project source in the folder.
I have added homepage:"." but no results. The application works fine with serve -s build from root of App but not with the express server!
import { Router, Request, Response } from 'express';
import { V1_Router } from './v1';
import path from 'path';
export const Routes = Router();
Routes
.use('/v1/', V1_Router)
.get('/*', async (_req: Request, res: Response) => {
res.sendFile(path.resolve('../public/build/index.html'));
});
I have checked the console no errors! All Javascript and CSS files are completely loaded just not running for some reason please help me...
Change it in something like that
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'public', 'build', 'index.html'));
});
app.listen(process.env.PORT || 8080);
EDIT1
app.use(express.static(path.join(__dirname, "..", "build")));
app.use(express.static("public"));
app.use((req, res, next) => {
res.sendFile(path.join(__dirname, "..", "build", "index.html"));
});

Compiling EJS to Static Files Guide?

I want to port my site to Netlify, which is a static website hosting. However, I have a ExpressJS server that uses EJS to render and route things and trying to put everything together without EJS is becoming a nightmare.
For example, server.js:
require('dotenv').config()
const express = require('express');
const app = express()
const PORT = process.env.PORT || 3000;
const path = require('path');
const panelRouter = require("./routes/panel.js")
app.set('view engine', 'ejs');
app.use("/assets", express.static(path.join(__dirname, 'views/assets')))
app.use("/panel", panelRouter)
function nocache(req, res, next) {
res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.header('Expires', '-1');
res.header('Pragma', 'no-cache');
next();
}
app.get("/", (req, res) => {
res.render("login");
});
app.get("/robots.txt", nocache, (req, res) => {
res.sendFile(path.join(__dirname + '/robots.txt'));
});
app.listen(port=PORT, () => {
console.log(`Listening on: ${PORT}`)
})
and one of the routers im showing, panelRouter (panel.js)
const express = require('express')
const router = express.Router();
router.get("/", (req, res) => {
res.render("../views/panel/home")
})
router.get("/about", (req, res) => {
res.render("../views/panel/about")
})
router.get("/messages", (req, res) => {
res.render("../views/panel/messages")
})
router.get("/achievements", (req, res) => {
res.render("../views/panel/achievements")
})
router.get("/events", (req, res) => {
res.render("../views/panel/events")
})
router.get("/exec", (req, res) => {
res.render("../views/panel/exec/home_exec")
})
router.get("/erg_home", (req, res) => {
res.render("../views/panel/erg_home")
})
module.exports = router;
Does EJS have a way to compile everything to a folder that I can easily deploy to Netlify or other sites that only host static files?

Using Express.js, how can I send a file on any request?

I'm trying to send index.html on any get request.
Code:
import express from 'express';
import path from 'path';
const app = express();
app.use(express.static(path.join(__dirname, '..', 'dist')));
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, '..', 'dist', 'index.html'));
res.end();
});
app.listen(8000, () => console.log('Server started on port 8000'));
change your
app.use(express.static(path.join(__dirname, '..', 'dist')));
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, '..', 'dist', 'index.html'));
res.end();
});
to
app.use(express.static(path.join(__dirname, '..', 'dist')));
app.get('*', function (req, res) {
res.sendFile('index.html', {root: path.join(__dirname, '..', 'dist')});
res.end();
});
A nice technique you can use here is to store the html page in the ram so your system doesn't have to read the file every time a request is made. I suggest you to use the fs library. Try the following.
import express from 'express';
const fs = require('fs')
const app = express();
var indexPage = fs.readFileSync(__dirname + '/PATH_TO/index.html', 'utf8')
app.get('*', function (req, res) {
return res.send(indexPage)
})
app.listen(8000, () => console.log('Server started on port 8000'));
With your current solution you try to read the file for every request. By doing the above you will save a lot of CPU power and provide a much faster result.

Can't handle routes using Express

I'm just starting out and I've got a barebones app here with a routes file ./routes/index.js.
When I browse to http://localhost:3000/index for example index.js is hit but none of the routes match and the program just goes straight through to "return router;". If I browse to http://localhost:3000/ I get the same again.
All the browser does is think about it for a bit and then give me a ERR_CONNECTION_RESET.
app.js
var express = require('express');
var logger = require('morgan');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var flash = require('connect-flash');
mongoose.connect('mongodb://localhost/blah');
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(flash());
app.use(require('./routes/index'));
module.exports = app;
index.js
var express = require('express');
var router = express.Router();
function authorize(req, res, next) {
if (true) {
next()
} else {
res.status(403).send('Forbidden')
}
}
module.exports = function(){
router.get('/index', function(req, res) {
res.send('index');
});
router.get('/hello/:name', function(req, res) {
res.send('hello ' + req.params.name + '!');
});
router.get('/', function(req, res) {
res.send('root');
});
return router;
}
app.js is missing a line to actually start the server. You need to add this:
app.listen(3000);
Got there in the end... I changed
module.exports = function(){
router.get('/index', function(req, res) {
res.send('index');
});
router.get('/hello/:name', function(req, res) {
res.send('hello ' + req.params.name + '!');
});
router.get('/', function(req, res) {
res.send('root');
});
return router;
}
to
router.get('/index', function(req, res) {
res.send('index');
});
router.get('/hello/:name', function(req, res) {
res.send('hello ' + req.params.name + '!');
});
router.get('/', function(req, res) {
res.send('root');
});
module.exports = router;

Resources