2013-09-29 71 views
18

我想使用Express發送AJAX請求。我運行的代碼如下所示:我如何使用Express框架製作AJAX請求?

var express = require('express'); 
var app = express(); 

app.get('/', function(req, res) { 
    // here I would like to make an external 
    // request to another server 
}); 

app.listen(3000); 

我該怎麼做?

回答

26

你不需要快遞進行傳出HTTP請求。使用該本機模塊:

var http = require('http'); 

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

var req = http.request(options, function(res) { 
    // response is here 
}); 

// write the request parameters 
req.write('post=data&is=specified&like=this'); 
req.end(); 
+1

文檔:https://開頭的NodeJS .org/api/http.html#http_http_request_options_callback – mauronet

34

您可以使用request

var request = require('request'); 
request('http://localhost:6000', function (error, response, body) { 
    if (!error && response.statusCode == 200) { 
    console.log(body) // Print the body of response. 
    } 
}) 
14

因爲你只是一個GET請求,我的建議是 https://nodejs.org/api/http.html#http_http_get_options_callback

var http = require('http'); 

http.get("http://www.google.com/index.html", function(res) { 

    console.log("Got response: " + res.statusCode); 

    if(res.statusCode == 200) { 
    console.log("Got value: " + res.statusMessage); 
    } 

}).on('error', function(e) { 
    console.log("Got error: " + e.message); 

}); 

該代碼是從該鏈接

+0

比頂級答案容易得多! – z3ntu