2014-01-11 42 views
0

我試圖重定向到一個新的網站並設置發送到該網站的發佈數據。我試過這個:重定向到新頁面並設置POST數據

var http = require('http'); 
http.createServer(function (req, res) { 
    res.writeHead(302, {"Location": "http://example.com/newpage/", "Content-Type": "application/x-www-form-urlencoded"}); 
    res.end("param1=value1&param2=value2"); 
}).listen(process.env.PORT, process.env.IP); 

這是不成功的。我如何重定向到一個新的網站並設置POST數據?

回答

0

簡單重定向無法發送發佈數據。 你必須提出一個新的請求和管道原始請求

http.createServer(function (req, res) { 
    var http = require('http'); 

    var post_data = JSON.stringify({aaa: 'abc', bbb: 123}); 

    var options = { 
    host: 'example.com', 
    port: '80', 
    path: '/', 
    method: 'POST', 
    headers: { 
     'Content-Type': 'application/x-www-form-urlencoded', 
     'Content-Length': post_data.length 
    }; 


    var req = http.request(options, function(resp_new) { 
    resp_new.setEncoding('utf8'); 

    resp_new.on('data', function(chunk){ 
     res.send(chunk); 
    }); 

    resp_new.on('end', function(){ 
     res.end(); 
    }); 
    }); 

    req.write(post_data); 
    req.end(); 
});