Angular/Production-texte-unique
De WikiSys
initialisation
cd ~Angular ng new production-texte-unique --style=scss --skip-tests=true routing y
cd production-texte-unique/ mkdir backend
- backend/emacs app.js
const express = require('express'); const app = express(); app.use((req, res) => { res.json({ message: 'Your request was successful!' }); }); module.exports = app;
- backend/server.js
const http = require('http'); const app = require('./app'); const port = process.env.PORT || 3000; app.set('port', port); const server = http.createServer(app); server.listen(process.env.PORT || 3000); console.log('Listening on port http://localhost:' + port);
If you try and make a request to your server, you should get back a JSON object containing the message we have specified.
git commit -m "backend/server.js backend/app.js localhost:3000 JSON message"
middleware
- backend/app.js
const express = require('express'); const app = express(); app.use((req, res, next) => { console.log('Request received'); next(); }); app.use((req, res, next) => { res.status(201); next(); }); app.use((req, res, next) => { res.json({ message: 'Your request was successful!' }); next(); }); app.use((req, res, next) => { console.log('Response sent successfully!'); }); module.exports = app;
- backend/server.js
const http = require('http'); const app = require('./app'); const normalizePort = val => { const port = parseInt(val, 10); if (isNaN(port)) { return val; } if (port >= 0) { return port; } return false; }; const port = normalizePort(process.env.PORT || '3000'); app.set('port', port); const errorHandler = error => { if (error.syscall !== 'listen') { throw error; } const address = server.address(); const bind = typeof address === 'string' ? 'pipe ' + address : 'port: ' + port; switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges.'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use.'); process.exit(1); break; default: throw error; } }; const server = http.createServer(app); server.on('error', errorHandler); server.on('listening', () => { const address = server.address(); const bind = typeof address === 'string' ? 'pipe ' + address : 'port ' + port; console.log('Listening on ' + bind); }); server.listen(port);