0

I’m trying to use Node.js to set up a proxy to Last.fm’s webservices. The problem is that every request to ws.audioscrobbler.com gets rewritten to www.last.fm. So for example $ curl http://localhost:8000/_api/test123 sends a 301 Moved Permanently to http://www.last.fm/test123.

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

// proxy server
var lastfmProxy = httpProxy.createServer(80, 'ws.audioscrobbler.com');

// target server
var app = express.createServer();
app.configure(function() {
  app.use('/_api', lastfmProxy);
});
app.listen(8000);

At the same time $ curl http://ws.audioscrobbler.com/test123 returns a regular 404 Not Found. I’m not exactly sure what I’m missing here, or if I’m approaching this completely the wrong way.

por
  • 23
  • 4

1 Answers1

2

The reason you get a 301 Moved Permanently is that ws.audioscrobbler.com gets an HTTP request with the hostname "localhost".

One solution is to let the proxy rewrite the hostname to "ws.audioscrobbler.com" before passing it on to the remote server:

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

var lastfmProxy = httpProxy.createServer(function (req, res, proxy) {
  req.headers.host = 'ws.audioscrobbler.com';
  proxy.proxyRequest(req, res, {
    host: 'ws.audioscrobbler.com',
    port: 80,
  });
}).listen(8000);
crishoj
  • 5,660
  • 4
  • 32
  • 31