mkdir pet-box && cd pet-box
npm init --yes
npm i express --save
touch server.js
const express = require('express');
const app = express();
app.set('port', process.env.PORT || 3000);
app.locals.title = 'Pet Box';
app.get('/', (request, response) => {
response.send('Oh hey Pet Box');
});
app.listen(app.get('port'), () => {
console.log(`${app.locals.title} is running on http://localhost:${app.get('port')}.`);
});
Cross Origin Resource Sharing (CORS) is a protocol that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served. This is in place for security reasons.
By default the CORS policy in express apps prevents you from making api calls from other domains. In order to allow api calls from other domains you need follow these two steps:
- Install cors as a dependency
npm install cors
- Near the top of the file, pull in the dependency
const cors = require('cors');
- Insert this config line into your server
file: app.use(cors());
Without it, you will get cors errors if you try to make a request from a react repo hosted at another domain. ie. trying to make requests from http://localhost:3000 to http://localhost:3001
First, let’s install the dependencies we’ll need for development:
npm install --save-dev @babel/core @babel/preset-env @babel/node
Next, we need a .babelrc
file in our root to define how to compile our code.
Inside of that file, add these contents:
// .babelrc
{
"presets": ["@babel/preset-env"]
}
Now, we can add a start script so that when we start our development server, it’ll use babel to compile our code into something node can understand. Add nodemon --exec babel-node server.js
as the start script.
You should be able to use imports/exports now and when you run npm start it’ll work error free! Your package.json should look something like:
"name": "pet-box",
"version": "1.0.0",
"main": "server.js",
"license": "MIT",
"dependencies": {
"express": "^4.16.4"
},
"devDependencies": {
"@babel/core": "^7.2.2",
"@babel/node": "^7.2.2",
"@babel/preset-env": "^7.3.1"
},
"scripts": {
"start": "nodemon --exec babel-node server.js"
}
}
Nodemon will auto-restart your server for you any time you make changes to your server file.
npm i -g nodemon
nodemon server.js
Make sure Postgres is installed and running. Don’t forget the semicolons in the the CREATE DATABASE command!
psql
`CREATE DATABASE publications;
Create a new directory and cd into it, then run npm init --yes. Install knex globally and in your project, and pg (postgres) in your project from npm:
npm i -g knex
npm i knex --save
npm i pg --save
We will use a knexfile to configure our database for all of our environments. Create that file using the below command with some default values:
→ knex init
Created ./knexfile.js