Enable CORS on an Express server | Link
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
First install it: npm i body-parser
var express = require('express);
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/', function(req, res) { console.log(req.body); }) app.listen(8000);
* In package.json check: "main": "app.js", then you can just run: nodemon instead of: nodemon app.js * npm i pug --save * mkdir view && cd_$ * touch index.pug * Then:
app.set('view engine', 'pug');
..
app.get('/', (req, res) => {
res.render('index', {title='Hello world!'});
});
* Pug templating 101 (Assume we have var colors = ['red', 'blue', 'green'])
doctype html
html(lang="en")
head
title= title
body
div.wrapper
.content
ul
each color in colors
li color
p#main Hi!
#secondary
if hint
p
i Hint: #{hint}
else
p (There is no hint)
* Pug locals
app.get('/cards', (req, res) => {
res.locals.prompt = "What is your question?";
res.locals.hint = "Think about something."; // interpolated from #{hint} above
res.render('card');
// res.render('card', {prompt: 'What is your...', hint: 'Think about...'});
});
* Pug Partials
...
header
include includes/header.pug
...
block content
...
include includes/footer.pug
In the index.pug file:
extends layout.pugblock content section#wrapper h1 Hello world!
.slice() takes two parameters, start(inclusive), end(exclusive) and returns an array of the items between start and end. If no second parameter is supplied, it takes all the items after the start.
console.log([0, 1, 2, 3, 4].slice(2, 4)); console.log([0, 1, 2, 3, 4].slice(2));
Math.random();
console.log(Math.floor(Math.random()*10));
All global variables are stored in the global object, that is window.
var myVar = 10;
console.log("myVar" in window);
console.log(window.myVar);