diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 0000000..8dc6807 --- /dev/null +++ b/.eslintrc @@ -0,0 +1,21 @@ +{ + "rules": { + "no-console": "off", + "indent": [ "error", 2 ], + "quotes": [ "error", "single" ], + "semi": ["error", "always"], + "linebreak-style": [ "error", "unix" ] + }, + "env": { + "es6": true, + "node": true, + "mocha": true, + "jasmine": true + }, + "ecmaFeatures": { + "modules": true, + "experimentalObjectRestSpread": true, + "impliedStrict": true + }, + "extends": "eslint:recommended" +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2c9b222 --- /dev/null +++ b/.gitignore @@ -0,0 +1,113 @@ + +# Created by https://www.gitignore.io/api/osx,linux,windows,node + +### OSX ### +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon +# Thumbnails +._* +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + + +### Windows ### +# Windows image file caches +Thumbs.db +ehthumbs.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + + +### Node ### +# Logs +logs +*.log +npm-debug.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules +jspm_packages + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity diff --git a/README.md b/README.md new file mode 100644 index 0000000..42ba958 --- /dev/null +++ b/README.md @@ -0,0 +1,32 @@ +# Vanilla HTTP server + +## General description + +This is a basic server app that a developer can access using GET and POST requests. The server will send responses to a developer notifying them of the request status. + +## How do I use this app? + +* Clone this repo and run the command `npm i` in your terminal to install all of the dependencies, including the cowsay API that embeds a server response in a cow illustration. + +* You will also need to run the command `brew install httpie`. For this app, the requests used in the terminal are formatted via HTTPie CLI. + +* Open 2 panes in your terminal to see how you, as the developer, can communicate with this server. + +* Be sure that you are in the root of the repo directory before attempting to initiate the port to the server. To do this, run `node server.js` in the first terminal pane. + * `server running:` followed by your PORT number should be logged in the terminal + +### GET requests + * **i.e.** 200 OK request: `http localhost:8000/cowsay text=='message'` + * You should receive a cowsay response with your embedded message. + * **i.e.** 200 OK request: `http localhost:8000` + * You should receive a response of `hello from my server!`. + * **i.e.** 400 BAD request: `http localhost:8000/cowsay text: 'message'` + * You should receive a cowsay response with a 'bad request' message. + +### POST requests + * **i.e.** 200 OK request: `http POST localhost:8000/cowsay text=message` OR `http POST localhost:8000/cowsay text='post request works'` + * You should receive a cowsay response with your embedded message. + * **i.e.** 400 BAD request: `http POST localhost:8000/cowsay` (no message attached to POST) + * You should receive a cowsay response with a 'bad request' message. + +GET and POST request commands should be ran in the second terminal pane. Notice that a GET request requires only 1 `=` while a POST request requires `==`. This is the proper HTTPie format for those requests. diff --git a/gulpfile.js b/gulpfile.js new file mode 100644 index 0000000..b16e376 --- /dev/null +++ b/gulpfile.js @@ -0,0 +1,23 @@ +'use strict'; + +const gulp = require('gulp'); +const eslint = require('gulp-eslint'); +const mocha = require('gulp-mocha'); + +gulp.task('test', function(){ + gulp.src('./test/*-test.js', {read: false}) + .pipe(mocha({reporter: 'spec'})); +}); + +gulp.task('lint', function(){ + return gulp.src(['**/*.js','!node_modules/**']) + .pipe(eslint()) + .pipe(eslint.format()) + .pipe(eslint.failAfterError()); +}); + +gulp.task('dev', function(){ + gulp.watch(['**/*.js','!node_modules/**'], ['lint', 'test']); +}); + +gulp.task('default', ['dev']); diff --git a/lib/parse-body.js b/lib/parse-body.js new file mode 100644 index 0000000..4a9c50f --- /dev/null +++ b/lib/parse-body.js @@ -0,0 +1,20 @@ +'use strict'; + +//exporting contents of module +module.exports = function(req, callback) { + req.body = ''; + + //accumulating data into the body + req.on('data', function(data) { + req.body += data.toString(); + }); + + req.on('end', function() { + try { + req.body = JSON.parse(req.body); + callback(null, req.body); + } catch (err) { + callback(err); + } + }); +}; diff --git a/package.json b/package.json new file mode 100644 index 0000000..e21ebd4 --- /dev/null +++ b/package.json @@ -0,0 +1,31 @@ +{ + "name": "07-vanilla-http-server", + "version": "1.0.0", + "description": "", + "main": "gulpfile.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "start": "node server.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/kcirekcom/07-vanilla-http-server.git" + }, + "keywords": [], + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/kcirekcom/07-vanilla-http-server/issues" + }, + "homepage": "https://github.com/kcirekcom/07-vanilla-http-server#readme", + "dependencies": { + "cowsay": "^1.1.9" + }, + "devDependencies": { + "chai": "^3.5.0", + "gulp": "^3.9.1", + "gulp-eslint": "^3.0.1", + "gulp-mocha": "^3.0.1", + "mocha": "^3.2.0" + } +} diff --git a/server.js b/server.js new file mode 100644 index 0000000..5d6782a --- /dev/null +++ b/server.js @@ -0,0 +1,47 @@ +'use strict'; + +const http = require('http'); +const url = require('url'); +const querystring = require('querystring'); +const cowsay = require('cowsay'); +const parseBody = require('./lib/parse-body.js'); +const PORT = process.env.PORT || 3000; + +const server = http.createServer(function(req, res) { + req.url = url.parse(req.url); + req.url.query = querystring.parse(req.url.query); + + if (req.method === 'POST') { + parseBody(req, function(err) { + if (err) console.error(err); + console.log('POST request body:', req.body); + if(req.url.pathname === '/cowsay' && req.body.text !== undefined) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end(cowsay.say({text: req.body.text.trim()})); + } + if(req.url.pathname === '/cowsay' && req.body.text === undefined) { + res.writeHead(400, {'Content-Type': 'text/plain'}); + res.end(cowsay.say({text: 'bad request'})); + } + }); + } + + if (req.method === 'GET' && req.url.pathname === '/') { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('hello from my server!'); + } + + if (req.method === 'GET' && req.url.pathname === '/cowsay' && req.url.query.text !== undefined) { + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end(cowsay.say({text: req.url.query.text.trim()})); + } + + if (req.method === 'GET' && req.url.pathname === '/cowsay' && req.url.query.text === undefined) { + res.writeHead(400, {'Content-Type': 'text/plain'}); + res.end(cowsay.say({text: 'bad request'})); + } +}); + +server.listen(PORT, () => { + console.log('server running:', PORT); +});