繁体   English   中英

如果我在前端使用 vanilla js 而在后端使用 node.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 而在后端使用 node.js,如何在 rest Apis 的同一端口上运行前端和后端? 我发现了很多关于如何做这个反应的东西,但没有关于香草 js 的东西。 有可能这样做吗?

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

在此处输入图像描述

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

注意:对于下面的代理检查

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

这是一个工作示例

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

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

公共/视图/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>

公共/样式/index.css

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

公共/脚本/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的 package 设置从一台 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}`);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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