Last active
April 9, 2019 19:30
-
-
Save MarioRinaldi/ea0a392b40cc279e8ce332d8149c8e82 to your computer and use it in GitHub Desktop.
api node + express + routes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const express = require('express'); | |
const fs = require("fs"); | |
const args = require('yargs').argv; | |
const app = express(); | |
const router = express.Router(); | |
const host = args.host || 'http://localhost'; | |
const port = args.port || 3030; | |
const public_response = "."; | |
const url = [host, port].join(':'); | |
router.get('/', function (req, res) { | |
const { msg } = req.query; // /?msg=foo | |
res.header("Access-Control-Allow-Origin", "*"); | |
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); | |
res.header("Access-Control-Allow-Methods", "GET,PUT"); | |
res.header('Access-Control-Allow-Credentials', 'true'); | |
res.status(200).send(msg || 'foo'); | |
}); | |
router.get('/:bar', function (req, res) { | |
const { bar } = req.params; // /foo | |
res.header("Access-Control-Allow-Origin", "*"); | |
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); | |
res.header("Access-Control-Allow-Methods", "GET,PUT"); | |
res.header('Access-Control-Allow-Credentials', 'true'); | |
// res.status(200).send('foo'); | |
res.status(200).json({data: bar}); | |
}); | |
router.post('/:foo', function (req, res) { | |
res.header("Access-Control-Allow-Origin", "*"); | |
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); | |
const { foo } = req.params; | |
if (foo === 'bar') { | |
res.status(200).json({success: "true"}); | |
} else if (foo === 'etc') { | |
res.status(401).json({ "code": 99, "message": "Unexpected error" }); | |
} else { | |
res.status(503).send(); | |
} | |
}); | |
app.use(router); | |
app.listen(port, function () { | |
console.log('Server running at', url); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment