Simple Restful API with Express (Cloud9 Compatible)

var express = require('express'); var app = express(); var cors = require('cors'); // --------------------------------------- // ALLOWING EXTERNAL DOMAINS TO REQUEST // --------------------------------------- cors({credentials: true, origin: true}); app.use(cors()); // --------------------------------------- // REQUEST HANDLING // --------------------------------------- app.get('/', function(req, res) { res.writeHead(200, {"Content-Type": "text/plain"}); res.end("Homepage, try /something to see some JSON"); }); app.get('/:data', function(req, res) { var data =; res.writeHead(200, {"Content-Type": "application/json"}); res.write( JSON.stringify({yourData: data}) ); res.end(); }); // --------------------------------------- // PORT LISTENING FOR CLOUD9 // --------------------------------------- app.listen(process.env.PORT, process.env.IP);
Step #1 -> In your terminal do "npm init" and you can press ENTER several times if you don't care about setting the description and other data.

Step #2 -> Install express and cors with this terminal command "npm install --save express cors".

Step #3 -> Create a file called server.js and paste the above code.

Step #4 -> Run the server and check your app in the browser.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.