Reputation: 4972
I am trying to add express inside my angular app to handle the communication with my server. I searched online about how to do it, and found out how. But I didn't understand few things.
I added a new file called server.js
:
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
//Get our API routes
const api = require('./server/routes/api');
const app = express();
//Parsers for POST Data app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }))
//Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));
//Set our API routes
app.use('/api', api);
// Catch all other routes and return the index file
app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'dist/index.html')); });
/** * Get port from environment and store in Express. */
const port = process.env.PORT || '3000'; app.set('port', port);
/** * Create HTTP server. */
const server = http.createServer(app);
/** * Listen on provided port, on all network interfaces. */
server.listen(port, () => console.log(`API running on localhost:${port}`));
And then I should add new folder called server
and inside of another folder called routes
and then an api.js
file:
const express = require('express');
const router = express.Router();
/* GET api listing. */
router.get('/', (req, res) => {
res.send('api works');
});
module.exports = router;
What the difference between these 2 files ? Can we combine them together ?
Upvotes: 0
Views: 144
Reputation: 23859
There is no difference between these two, except that the second one should only be used to define your own API routes, and yes, these can be combined if you want, but that will result in server.js
becoming bulky.
The main idea here is to separate the concerns. server.js
can be used to configure server level things, i.e. error handling, CORS configuration etc. On the other hand, api.js
should be used to define your API routes.
Ultimately, server.js
is what will be used to boot up your Node server, and if you see closely, this file internally uses api.js
.
const api = require('./server/routes/api');
...
...
app.use('/api', api);
Upvotes: 1