2011-10-14 55 views
0

我試圖使用Node.js爲Last.fm的webservices設置代理。問題是,對ws.audioscrobbler.com的每個請求都被重寫爲www.last.fm.因此,例如$ curl http://localhost:8000/ _api/test123發送301 Moved Permanentlyhttp://www.last.fm/test123ws.audioscrobbler.com的Node.js代理以301響應www.last.fm

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); 

同時$ curl http://ws.audioscrobbler.com/test123返回普通的404 Not Found。我不完全確定我在這裏錯過了什麼,或者如果我以完全錯誤的方式接近它。

回答

2

您得到301 Moved Permanently的原因是ws.audioscrobbler.com獲取主機名爲「localhost」的HTTP請求。

一種解決方案是讓代理重寫主機名「ws.audioscrobbler.com」將它傳遞到遠程服務器之前:

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); 
+0

這是有道理的。謝謝! – por