使用http.get中的数据更新app.get响应

我使用快递和传递path作为URL参数。

app.get("/download", function (req, res) { var location; var options = { host: 'example.com', port: 80, path: req.query.url.replace(/ /g, "%20") }; http.get(options, function (res) { // get location from this location = res.headers.location; console.log(location); }).on('error', function (e) { console.log("Got error: " + e.message); }); // it won't get the location data since http.get is async // so how could I send this response using the data from http.get res.setHeader('Content-Type', 'text/html'); res.send(location); }); 

在这段代码中,我希望从http.get的请求头获取数据用于在浏览器上进行渲染。

无论如何,我可以做在浏览器上呈现http.get数据。

你不能只是移动res.send()内的函数,例如:

 app.get("/download", function (req, res) { var location; var options = { host: 'example.com', port: 80, path: req.query.url.replace(/ /g, "%20") }; http.get(options, function (response) { // get location from this location = response.headers.location; console.log(location); res.setHeader('Content-Type', 'text/html'); res.send(location); }).on('error', function (e) { console.log("Got error: " + e.message); res.send('Error...') }); }); 

我还build议使用请求包进行HTTP请求,因为它可以使整个过程更简单。

您可以通过使用中间件将“GET”查询中的数据传递给example.com 。 中间件将拦截对应用程序的任何请求,执行其中定义的任何操作,并将控制权交还给该请求的处理程序。

 // Define middleware that makes a 'GET' request to 'example.com' and obtains the location. app.use(function(req, res, next) { var options = { host: 'example.com', port: 80, path: req.query.url.replace(/ /g, "%20") }; http.get(options, function (res) { // Attach the location to the request object. This will be present // in the request object of the 'GET' handler for the app. req.webLocation = res.headers.location; // Execute the next middleware or the route handler if there's no // other middleware. next(); }).on('error', function (e) { console.log("Got error: " + e.message); }); }); app.get("/", function (req, res) { res.setHeader('Content-Type', 'text/html'); // Render the 'webLocation' obtained from the middleware. res.send(req.webLocation); });