简体   繁体   中英

Start expressjs server when browser opens

I have a basic Expessjs server and can run it with npm start . I can also build it with npm run build . This way, dist/main.js file created. I want my expressjs server run when I open the index.html. However, below error happens when index.html is opened. I don't need es5 compatibility. So, not using babel.

Thanx

在此处输入图像描述

When I change to target: ['web'], 32 fallback error hapens like;

在此处输入图像描述

Is my use case reasonable? If so, how to do it?

Details are like these;

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>

No, your use case is not reasonable, unfortunately. You are trying to run a Nodejs server in the browser.

The other way works tho, you have to run the server so you can display the index.html file. You would need to add a new route handler to your server.js file to point all other request to the index.html file (or you can 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'));
});

...

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