简体   繁体   中英

How to run frontend and backend on same port , if I am using vanilla js on frontend and node js on backend?

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

在此处输入图像描述

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}`);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM