Setting Up a Backend Project with Node.js

Classified in Computers

Written at on English with a size of 5.14 KB.

To start a backend project.

- npm init

Then make a file with whatever entry point you named it as, for example, server.js

Once package.json is created:

  • npm i <package>
  • connect-mongo (store sessions in DB)
  • dotenv (for config files, environment variables)
  • express
  • mongoose
  • express-sessions (sessions and cookies)
  • method-override (to use PUT, UPDATE, DELETE requests)
  • moments (date formatting)
  • morgan (logging)
  • passport (authentication)

npm i -D <package>

  • nodemon (Update every file change instantly without having to restart the server)
  • cross-env (To update environment variables in script definition itself)

After installing the dependencies, edit the scripts in package.json

"start": "cross-env NODE_ENV=production node server.js",
"dev": "cross-env NODE_ENV=development nodemon server.js"

The initial setup is now done.

Now in server.js, get express and dotenv.

constexpress=require("express");
const dotenv =require("dotenv");

To load the config file:

dotenv.config({path: <path to .env file>});

Then to load express:

const app = express();

Create a database collection in MongoDB compass or in MongoDB atlas, then store the connection string.

If you created the database in compass, then the connection string will be:

mongodb://localhost:27017/<project name>

If you take the connection string from atlas, then it will be of the form:

mongodb+srv://<username>:<password>@<user>cluster.cbmll.mongodb.net/<dbname>?retryWrites=true&w=majority

Once you copy this, store this string into an environment variable in your .env file.

You can access env variables using "process.env".

To start the server:

app. listen(<port number>, <some function>);

To run:

npm run <script name>

Ex: npm run dev or npm run start from the above script example

To connect to the database:

First get mongoose:

const mongoose = require("mongoose");

Then:

constconnectDB=async () => {
try {
constconn=awaitmongoose.connect(process.env.MONGO_URI, {});
  } catch (err) {
console.error(err);
process.exit(1);
  }};

This connects to the database, and as it returns a promise, we run it as an async function. If it doesn't connect, it terminates the program.

To define what happens in a particular route:

In index.js file in a routes folder:

const router = express.Router();

router.get('/<path>', (req, res) => {

  //functionality

})

module.exports = router;

Back in server.js:

const routes = require("./routes/index");

app.use("/<path>", routes);

Entradas relacionadas: