浏览器打开时启动 expressjs 服务器

时间:2021-03-28 11:31:00

标签: express webpack

我有一个基本的 Expessjs 服务器,可以用 npm start 运行它。我也可以使用 npm run build 构建它。这样,dist/main.js 文件创建。当我打开 index.html 时,我希望我的 expressjs 服务器运行。但是,打开 index.html 时会发生以下错误。我不需要 es5 兼容性。所以,不要使用 babel。

谢谢

enter image description here

当我更改为 target: ['web'], 时,会出现 32 个回退错误;

enter image description here

我的用例合理吗?如果是,怎么做?

细节是这样的;

src/server.js

const express = require("express");
const path = require("path");
const bodyParser = require('body-parser');

const app = express();

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
    res.header(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept"
    );
    next();
});

app.get("/api/ping", (request, response) => {
    console.log("❇️ Received GET request to /api/ping");
    response.json({ reply: "GET pong!" });
});

app.post("/api/ping", (request, response) => {
    console.log("❇️ Received POST request to /api/ping");
    response.json({ reply: "POST pong!" });
});

// Express port-switching logic
let port = 3001;

// Start the listener!
const listener = app.listen(port, () => {
    console.log("❇️ Express server is running on port", listener.address().port);
});

package.json

{
  "name": "webpack-basic",
  "version": "1.0.0",
  "description": "",
  "private": "true",
  "scripts": {
    "build": "webpack",
    "start": "node src/server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^5.28.0",
    "webpack-cli": "^4.6.0"
  },
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1"
  }
}

webpack.config.js

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

module.exports = {
    target: ['node'],
    entry: "./src/server.js",
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "main.js",
    },
};

dist/index.html

<body>
    <div id="root" />
    <script src=" ./main.js "></script>
</body>

1 个答案:

答案 0 :(得分:1)

不,不幸的是,您的用例不合理。您正在尝试在浏览器中运行 Nodejs 服务器。

另一种方法是有效的,您必须运行服务器才能显示 index.html 文件。您需要向 server.js 文件添加新的路由处理程序,以将所有其他请求指向 index.html 文件(或者您可以 use a template engine):

const path = require('path');
...

app.get("/api/ping", (request, response) => {
    console.log("❇️ Received GET request to /api/ping");
    response.json({ reply: "GET pong!" });
});

app.post("/api/ping", (request, response) => {
    console.log("❇️ Received POST request to /api/ping");
    response.json({ reply: "POST pong!" });
});

app.use((req, res) => {
  res.sendFile(path.join(__dirname, './index.html'));
});

...