nodejs

2 posts

Simple alternative to nvm using Docker

After Node v6.6.0 is out, I wanted to try it, but I don't want to replace my local Node v4 environment. I can use nvm, but that's too much for some simple tests. So I switched to Docker.

Just adding following alias to my .zshrc file, I can now run JavaScript file using Node 6.

alias node6="docker run -it --rm -v $(pwd):/code -w /code node:6.6 node"  
node6 hello.js  

I also added Node 4.

alias node4="docker run -it --rm -v $(pwd):/code -w /code node:4.5 node"  

NodeJS API proxy with CORS support

Our application's backend is Java-based and exports REST API, frontend is AngularJS-based. During frontend development, use Grunt connect to start the development server for CoffeeScript/LESS and static files. To enable AngularJS to access the API which running on different port, we need a proxy with CORS support. So I created a simple proxy server using connect and node-http-proxy.

The proxy code is very simple. In the code below, API server is running on port 8080 and proxy server is running on port 8000. The proxy server sets Access-Control-* headers to enable CORS support. It also provides basic authentication header.

var connect = require('connect'),  
  httpProxy = require('http-proxy');

var app = connect();

var proxy = httpProxy.createProxyServer({  
  target: 'http://127.0.0.1:8080'
});

proxy.on('proxyReq', function(proxyReq, req, res, options) {  
  proxyReq.setHeader('Authorization', 'Basic YWRtaW46cGFzc3dvcmQ=');
});

proxy.on('error', function(e) {  
  console.log(e);
});

app.use(function(req, res, next) {  
  if (req.headers['origin']) {
    res.setHeader('Access-Control-Allow-Origin', req.headers['origin']);
    res.setHeader('Access-Control-Allow-Methods', 'POST, PUT, GET, OPTIONS, DELETE');
    res.setHeader('Access-Control-Max-Age', '3600');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, Authorization, Content-Type');
  }
  if (req.method !== 'OPTIONS') {
    next();
  }
  else {
    res.end();
  }
});

app.use(function(req, res) {  
  proxy.web(req, res);
});

app.listen(8000);  
console.log('Proxy server started.')  

AngularJS needs to have cross-domain requests enabled.

app.config(function($httpProvider) {  
  $httpProvider.defaults.useXDomain = true
});

Then you should be able to access the API.