[英]Update app.get response with data from http.get
我正在使用express和傳遞路徑作為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...')
});
});
我還建議使用請求包來發出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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.