如果我在前端使用 vanilla js 而在后端使用节点 js,如何 运行 前端和后端在同一端口上?

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

如果我在前端使用 vanilla js 而在后端使用节点 js,如何 运行 在 rest Apis 的同一端口上使用前端和后端?我发现了很多关于如何做这个反应的东西,但没有关于香草 js 的东西。可以这样做吗?

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

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

注意:用于代理检查

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

这是一个工作示例

  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 响应

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

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

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