2.6 KiB
Node.js
NPM
Whenever creating a new node project, use to set it up
npm init
NPM is a package manager for node.js and js libraries and frameworks. You can look up packages there, and install them for your project with:
npm install package-name --save
module.exports/require
Traditionally, importing JS files into other JS files has not been supported... until now! There are several ways to do this, but node allows you to add things the to module.exports object.
module.exports = 'foo';
Whatever is on there, will be the return value of
require('yourJSFile.js');
You can assign this to a variable to use later
Instantation
First require express:
var express = require('express'); //include express package
express has lots of abilities, but we just want to start up a server app:
var app = express(); // create an express app
Then make it listen on a port
app.listen(3000, function(){ //start the server
console.log('listening on port ' + PORT);
});
CRUD and HTTP Verbs
In comp sci, there are different kinds of action you can take on data
- create
- read
- update
- destroy
There are different kinds of 'methods' you can use to make a request to a server that map to these actions:
- post (create)
- get (read)
- put/patch (update)
- delete (delete)
PUT is for updating an entire model, PATCH is for changing just a few attributes
Routing
Basic routing can be done at the app level
app.get('/', function(req, res){ // route for /
res.send('hi'); //respond with 'hi'
});
This sets up an event listener for any GET request that comes into the server with the path of /. Give it a callback function which takes a request variable and a respond variable. Each of these have different methods/properties which we'll learn about
This can get difficult to maintain with a lot of variables, so we can group urls together
var runsController = require('./controllers/runs.js'); //require our own runsController
app.use('/runs/', runsController); //use it for anything starting with /runs
Now, in a separate file, we can use:
var controller = require('express').Router(); //require express and create a router (controller)
controller.get('/', function(req, res){ //route for finding all routes by a the session user
res.send('runs index');
});
module.exports = controller;