Home > Mobile >  How to host a React app in Nodejs without using Express?
How to host a React app in Nodejs without using Express?

Time:12-21

I know the standard way is to use Express, but i was wondering how i could achieve this without having to use it. I already know how to serve html files using http/https in a common website (without a frontend framework) through nodejs, but when i tried to do the same with index.html from React app, it wouldn't work. I think it's important to mention that i am using react-router. I searched a lot about this but every tutorial would use Express, so i couldn't find help in google.

Here's how i would do with plain html:

const server = http.createServer( async (req, res) => {

res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');

const requestUrl = url.parse(req.url);
let completePath = requestUrl.pathname;
let path = completePath.split('/').slice(1)[0];

let fileContent;

if(path == "")
    path = "index.html";

try{
    fileContent = fs.readFileSync(path);
    res.end(fileContent, 'utf-8');
}
catch(err){
    console.log("File not found: "   path);
    if(path != "favicon.ico"){
        res.statusCode = 404;
        fileContent = fs.readFileSync("404.html");
        res.end(fileContent);
    }
}


});

Thanks!

CodePudding user response:

Ok, i eventually got it:

const fs = require('fs');
const https = require('http');

const hostname = 'localhost';
const port = 3000;


const server = https.createServer( async (req, res) => {

    res.statusCode = 200;
    let root = "./build";

    let path = root   req.url;

    let fileContent;

    if(path == root   "/")
        path = path   "index.html";

    try{
        fileContent = fs.readFileSync(path);
        res.end(fileContent, 'utf-8');
    }
    catch(err){
        if(req.url != "/favicon.ico"){
            fileContent = fs.readFileSync(root   "/index.html");
            res.end(fileContent);
        }
    }

});

server.listen(port, hostname, () => {
    console.log("Server listening on "   port);
});

as opposed to Express version:

const express = require("express");
const app = express();

// this throws everything to the user
app.use(express.static(__dirname   "/build"));

// this redirects everything to index.html
app.get('*', (req, res) => {
    res.sendFile(__dirname   "/build/index.html");
});


app.listen(port, hostname, () => {
    console.log("Server listening on "   port);
});
  • Related