【问题标题】:How to run frontend and backend on same port , if I am using vanilla js on frontend and node js on backend?如果我在前端使用 vanilla js,在后端使用 node js,如何在同一端口上运行前端和后端?
【发布时间】:2021-07-10 15:40:06
【问题描述】:

如果我在前端使用 vanilla js,在后端使用 node js,如何在 rest APIs 的同一端口上运行前端和后端?我发现了很多关于如何为 react 执行此操作的内容,但对 vanilla js 却一无所获。有可能吗?

有关更多信息,您还可以阅读这篇文章:- https://medium.com/@ryanchenkie_40935/react-authentication-how-to-store-jwt-in-a-cookie-346519310e81

【问题讨论】:

  • 您不能在同一个端口上为同一个设备同时运行前端和后端。例如,如果您在 localhost 3000 上运行前端,那么您应该在另一个类似 localhost 3001 上运行后端。
  • 这能回答你的问题吗? Can two applications listen to the same port?
  • 然后,如何通过在 react 应用程序的 package.json 文件中设置代理字段,反应应用程序及其后端如何在本地主机的相同端口上运行,我还添加了一个图像来证明这一点

标签: javascript html node.js express httpserver


【解决方案1】:

您的 NodeJS 应用程序可以为您的 HTML 页面和静态资产(例如 Javascript 和 CSS 代码)提供服务。

注意:用于代理检查below

您可以通过 express.static 使用 Express 来提供静态内容。

这是一个工作示例

  1. 创建以下目录结构
+-- public
|   +-- scripts
|   |  +-- index.js
|   +-- styles
|   |  +-- index.css
+-- +-- views
|   |  +-- index.html
+-- index.js
+-- package.json
  1. 添加您的代码

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. 运行npm init创建package.json文件

  2. 运行npm install express --save

  3. 使用node index.js启动服务器

  4. 导航到http://localhost:7000/public/views/ 以获取 HTML 页面

  5. 导航到http://localhost:7000/user 以获取 JSON 响应

现在您的服务器已准备好接收请求。您可以将客户端代码添加到公用文件夹中,将服务器端代码添加到公用文件夹之外。

您现在有一个端口来接收所有前端和后端请求。

在 OP 关于使用代理的评论后更新

我们还可以使用名为 http-proxy-middleware 的包设置从一个 NodeJs 服务器到另一个服务器的代理

这是代理的基本设置


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

【讨论】:

  • 这是服务器端渲染,我想保持我的前端和后端解耦,然后想在本地主机的同一端口上运行它。
  • 在此我们向客户端提供静态 HTML 内容。我们没有使用 HTML 模板。因此,从技术上讲,它不是服务器端渲染。甚至您的 react 应用程序也使用 Node 服务器来提供静态内容。你说你可以在反应中做到这一点,我很想知道更多关于它是如何在反应中完成的。因为 afaik,两个不同的应用程序不可能使用 TCP 连接在单个端口上运行。
  • 您分享的中篇文章是从 create-react-app 节点服务器到您的代理 url 的代理。您也可以像这样设置代理。您可以使用包 http-proxy-middleware 包并设置从一个端口到另一个端口的代理。
  • 如果您有兴趣,我已经添加了代理逻辑。
  • 是的,如果你愿意,那就太好了
猜你喜欢
  • 2018-09-21
  • 1970-01-01
  • 2023-04-07
  • 2022-11-28
  • 2021-11-28
  • 2021-05-22
  • 2019-06-29
  • 2017-11-22
  • 1970-01-01
相关资源
最近更新 更多