What I’m trying to achieve is that when I access http://localhost:3000/app it displays myFile.html and when I access http://localhost:3000/api it returns "It worked!".
So far I have these two files:
App.js:
const http = require('http');
const fs = require('fs');
const express = require('express');
const app = express();
app.use(express.static("./"));
app.get("/app", (request, response) => {
fs.readFile("./myFile.html", "utf8", (err, html) => {
if (err) {
response.status(500).send("A problem occured" + err);
}
response.send(html);
})
});
app.listen(process.env.PORT || 3000, () => console.log("App available on http://localhost:3000"));
server.js:
const http = require('http');
const fs = require('fs');
const express = require('express');
const app = express();
app.use(express.static("./"));
app.get("/api", (request, response) => {
response.send("It worked!");
});
app.listen(process.env.PORT || 3000, () => console.log("App available on http://localhost:3000"));
The problem is that sometimes it works and sometimes it doesn’t – I get the Cannot GET /app or Cannot GET /api errors respectively. I’ve determined that when I run node App.js and node server.js then the one which I run last works excpected… But sometimes they both work. I know that this is very confusing, but I can’t really figured out when exactly it works.
>Solution :
You can’t run two servers on the same port. And each URL doesn’t need to be its own entire server.
Include both endpoints in one server:
const http = require('http');
const fs = require('fs');
const express = require('express');
const app = express();
app.use(express.static("./"));
// one URL endpoint
app.get("/app", (request, response) => {
fs.readFile("./myFile.html", "utf8", (err, html) => {
if (err) {
response.status(500).send("A problem occured" + err);
}
response.send(html);
})
});
// another URL endpoint
app.get("/api", (request, response) => {
response.send("It worked!");
});
app.listen(process.env.PORT || 3000, () => console.log("App available on http://localhost:3000"));
Alternatively, if you do want them to be separate servers, they need to run on separate ports. (Or they can run on the same port on separate computers.)