require express server.js
const express = require('express')const app = express() app.get('/', function (req, res) { res.send('Hello World')}) app.listen(3000)
require express server.js
const express = require('express')const app = express() app.get('/', function (req, res) { res.send('Hello World')}) app.listen(3000)
expressjs server
// npm init
// npm i express
const express = require('express');
const server = express();
const PORT = 3000;
// Body parser
server.use(express.json());
// Homme page
server.get('/', (req, res) => {
return res.send("<h1 style='text-align: center;'>Hello,<br />from the Express.js server!</h1>");
})
// About page
server.get('/about', (req, res) => {
return res.send('<h2 style="text-align:center">About us</h2>');
})
// 404 page
server.use((req, res, next) =>{
res.status(404);
// respond with html page
if (req.accepts('html')) {
res.sendFile(__dirname + '/error404.html');
return;
}
// respond with json
else if (req.accepts('json')){
res.send({
status: 404,
error: 'Not found'
});
return;
}
// respond with text
else {
res.type('txt').send('Error 404 - Not found');
}
});
// Listening to the port
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
// Running the server: node server.js
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us