1

How to run frontend and backend on same port in rest Apis , if I am using vanilla js on frontend and node js on backend? I found a lot of stuff regarding how to do this for react but nothing about vanilla js. Is it possible to do so?

For more information you can also read this article :- https://medium.com/@ryanchenkie_40935/react-authentication-how-to-store-jwt-in-a-cookie-346519310e81

enter image description here

BHANU ARORA
  • 81
  • 1
  • 8
  • you can not run both front end and backend on same port for same devcie. For example if you are running front end on localhost 3000 then you should run backend on another like localhost 3001. – Gulshan Aggarwal Jul 10 '21 at 15:42
  • Does this answer your question? [Can two applications listen to the same port?](https://stackoverflow.com/questions/1694144/can-two-applications-listen-to-the-same-port) – Tushar Shahi Jul 10 '21 at 15:57
  • Then How a react application and its backend can run on same ports of localhost by setting a proxy field in package.json file of react application , I am also adding an image justifying this – BHANU ARORA Jul 11 '21 at 05:09

1 Answers1

0

Your NodeJS application can serve your HTML pages and static assets such as Javascript and CSS codes.

Note: for proxy check below

You can use Express to serve static content by using express.static.

Here is a working example

  1. Create a following directory structure
+-- public
|   +-- scripts
|   |  +-- index.js
|   +-- styles
|   |  +-- index.css
+-- +-- views
|   |  +-- index.html
+-- index.js
+-- package.json
  1. Add your code

index.js

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

const app = express();

// add relevant request parsers
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.text());

app.set("views", path.join(__dirname, "/public/views"));
// set jade as view engine. 
app.set("view engine", "jade");

// public route will be used to server the static content
app.use("/public", express.static("public"));

// write your APIs here

app.get("/user", (req, res) => {
    res.json({
        firstname: "john",
        lastname: "doe"
    });
});

const port = 7000;

app.listen(port, () => {
    console.log(`Server is running on port: ${port}`);
});

public/views/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/public/styles/index.css" type="text/css" >
    <script src="/public/scripts/index.js"></script>
    <title>Document</title>
</head>
<body>
    <h1>Hello World</h1>
</body>
</html>

public/styles/index.css

body {
    color: white;
    background-color: black;
}

public/scripts/index.js

window.onload = () => {
    alert("script loaded");
}
  1. Run npm init to create package.json file

  2. Run npm install express --save

  3. Start the server using node index.js

  4. Navigate to http://localhost:7000/public/views/ to get the HTML page

  5. Navigate to http://localhost:7000/user to get the JSON response

Now your server is ready to receive requests. You can add your client-side code in the public folder, and server-side code outside the public folder.

You now have a single port to receive all your front-end and backend requests.

UPDATE after OP's comment on using proxies

We can also set up a proxy from one NodeJs server to another Server using a package called http-proxy-middleware

Here is the basic setup of proxy


const express = require("express");
const { createProxyMiddleware } = require("http-proxy-middleware");

const app = express();

const proxyUrl = "http://localhost:3000";
const proxy = createProxyMiddleware({
    target: proxyUrl,
});

app.use('/api', createProxyMiddleware(proxy));

const port = 7000;

app.listen(port, () => {
    console.log(`Server is running on port: ${port}`);
    console.log(`Proyx is set to ${proxyUrl}`);
});

Amir Saleem
  • 2,912
  • 3
  • 21
  • 35
  • this is server side rendering and I want to keep my frontend and backend decoupled, and then want to run it on same port of localhost. – BHANU ARORA Jul 11 '21 at 09:13
  • In this we are serving static HTML content to the client. We are not using HTML templates. So, technically it's not server side rendering. Even your react application uses a Node server to serve the static content. You said that you can do this in react, I am interested to know more about how it's done in react. Because afaik, it is not possible for two different applications to run on a single port using a TCP connection. – Amir Saleem Jul 11 '21 at 09:34
  • The medium article.which you've shared does the proxy from create-react-app node server to your proxy url. You can also setup a proxy like this. You can use a package http-proxy-middleware package and setup a proxy from one port to another. – Amir Saleem Jul 11 '21 at 09:39
  • I've added a proxy logic if you are interested. – Amir Saleem Jul 11 '21 at 09:48
  • yeah sure , it will be great if you – BHANU ARORA Jul 23 '21 at 09:43
  • check the code snippet in the end, it has proxy logic – Amir Saleem Jul 23 '21 at 10:42