Q:

express and node

basic server

const express =require('express');
const app = express();
const PORT = 5000;


app.get('/',(req,res)=>{
   res.json({message: 'Welcome to the backend'})
})


app.listen(PORT ,()=>console.log(`Connected to ${PORT}`)
           
           
10
// Load HTTP module
const http = require("http");

const hostname = "127.0.0.1";
const port = 8000;

// Create HTTP server 
const server = http.createServer((req, res) => {

   // Set the response HTTP header with HTTP status and Content type
   res.writeHead(200, {'Content-Type': 'text/plain'});
   
   // Send the response body "Hello World"
   res.end('Hello World\n');
});

// Prints a log once the server starts listening
server.listen(port, hostname, () => {
   console.log(`Server running at http://${hostname}:${port}/`);
})
4
// node js -> express -> basic example: static folder, 404 page

const express = require('express');
const path = require('path');
const PORT = process.env.PORT || 5000;

const app = express();

function error404(req, res) {
  res.status(404);

  if (req.accepts('html')) {
    res.sendFile(path.join(__dirname, 'public/errors/404.html'));
    return;
  }

  if (req.accepts('json')) {
    res.send({
      status: 404,
      error: 'Not found'
    });
    return;
  }
  
  res.type('txt').send('404 - Not found');
}

app
  .use(express.static(path.join(__dirname, 'public')))
  .use(error404)
  .listen(PORT, () => console.log(`Listening on ${ PORT }`));
1

New to Communities?

Join the community