npm i -g nodemon
Auto-generate a package.json (with default ‘yes’ to each of the standard questions) using:
npm init --yes
mkdir NAME_OF_DIRECTORY
npm i express --save
touch server.js
touch app.js
CORS
npm install cors
Near the top ofapp.js
include:const cors = require(‘cors’);
Insert this config line into yourapp.js
file:app.use(cors());
In your app.js
file enter this:
const express = require('express');
const app = express();
app.use(express.json());
app.get('/', (request, response) => {
response.send('NAME OF APP');
});
export default app;
In your server.js
file enter this:
import app from ‘./app’;
app.set('port', process.env.PORT || 3000);
app.listen(app.get('port'), () => {
console.log(`${app.locals.title} is running on http://localhost:${app.get('port')}.`);
});
npm install --save-dev @babel/core @babel/preset-env @babel/node
Create a.babelrc
file in the root of your directorytouch .babelrc
Inside that file add this:
// .babelrc
{
"presets": ["@babel/preset-env"]
}
In your package.json
file within your “scripts” object replace the “start” with this:
"start": "nodemon --exec babel-node server.js"
npm i -g knex
npm i knex --save
npm i pg --save
Create a knex file in your terminal usingknex init
Your./knexfile.js
should look something like this:
module.exports = {
development: {
client: 'pg',
connection: 'postgres://localhost/<NAME OF DATABASE>
migrations: {
directory: './db/migrations'
},
seeds: {
directory: './db/seeds/dev'
},
useNullAsDefault: true,
},
test: {
client: 'pg',
connection: 'postgres://localhost/<NAME OF DATABASE>
migrations: {
directory: './db/migrations'
},
seeds: {
directory: './db/seeds/test'
},
useNullAsDefault: true,
},
};
Server-Side Testing With A DB (Database)
npm i jest -g
We’ll need to set up our app.js and test file to have access to our database, regardless of whether we’re using the development DB or the test DB. Add the following to your own app.js, as well as app.test.js:
const environment = process.env.NODE_ENV || 'development'
const configuration = require('./knexfile')[environment]
const database = require('knex')(configuration)
Make sure Postgres is installed and running:
- Open your terminal Type in:
psql
CREATE DATABASE NAME_OF_DATABASE;
(don’t forget the semicolons!)- Check Postgres/Postico to make sure the database(s) are there.
- CD into your backend directory and in your terminal run:
Add
npm install supertest