【问题标题】:Accessing http request objects outside the functions scope in Node.js在 Node.js 中访问函数范围之外的 http 请求对象
【发布时间】:2018-08-14 20:45:54
【问题描述】:

我有这段代码可以向 API 发出请求

var request = require('request');


 request('http://www.google.com', function (error, response, body) {
 console.log('error:', error); // Print the error if one occurred
 console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
 console.log('body:', body); // Print the HTML for the Google homepage.
    });

但是,我也是在我的节点应用程序中提供服务的路线,我得到的响应超出了路线的范围。我想使用 EJS 将我的请求中的值添加到视图中,但是使用 EJS 我必须在.render() 中定义文件要使用的值,并且似乎不可能获得这些值。

我的 app.js 看起来像这样

const express = require('express');
var request = require('request');
const path = require('path');
const chalk = require('chalk');

const app = express();
const port = process.env.PORT || 3000; // Port number

// var url = 'http://api.openweathermap.org/data/2.5/forecast?id=1253573&APPID=56e2043a628c776ab619d9d393c2b568&units=metric'; // API Request URL

app.use(express.static(path.join(__dirname, '/public/')));
app.use('/css', express.static(path.join(__dirname, '/node_modules/bootstrap/dist/css')));
app.use('/js', express.static(path.join(__dirname, '/node_modules/bootstrap/dist/js')));
app.use('/js', express.static(path.join(__dirname, '/node_modules/jquery/dist')));
app.set('views', './views');
app.set('view engine', 'ejs');


function apiCall(callback) {
  request(url, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var result = JSON.parse(body);
      // console.log(result);
      return callback(result, false);
    } else {
      return callback(null, error);;
    }
  });
}

app.get('/', (req, res) => {
  const url = 'http://api.openweathermap.org/data/2.5/forecast?id=1253573&APPID=56e2043a628c776ab619d9d393c2b568&units=metric'; // API Request URL

  const x = request(url, function (error, response, body){
  const result = JSON.parse(x.body);
  console.log(result);

  });
  res.render('index',{
      //temp: data.list[0].main.temp,
      place : result.city['name'] // || data.city['name'],
      //wind: data.list[0].wind.speed,
      //desc: data.list[0].weather[0].description,
      }
    );
    });

app.listen(port, () => {
  console.log(`listening on port ${chalk.green(port)}`);
});

任何帮助将不胜感激!

【问题讨论】:

标签: javascript node.js http python-requests


【解决方案1】:

const request = require('request');
const express = require('express');
const path = require('path');
const chalk = require('chalk');

const app = express();
const port = process.env.PORT || 3000; // Port number

app.use(express.static(path.join(__dirname, '/public/')));
app.use('/css', express.static(path.join(__dirname, '/node_modules/bootstrap/dist/css')));
app.use('/js', express.static(path.join(__dirname, '/node_modules/bootstrap/dist/js')));
app.use('/js', express.static(path.join(__dirname, '/node_modules/jquery/dist')));
app.set('views', './views');
app.set('view engine', 'ejs');


function apiCall(url, callback) {
  request(url, function(error, response, body) {
    if (!error && response.statusCode == 200) {
      var result = JSON.parse(body);
      // console.log(result);
      return callback(null, result);
    } else {
      return callback(error, null);;
    }
  });
}

app.get('/', (req, res) => {
  const url = 'http://api.openweathermap.org/data/2.5/forecast?id=1253573&APPID=56e2043a628c776ab619d9d393c2b568&units=metric'; // API Request URL

  apiCall(url, (err, body) => {
	if(err) {
    	// handle error
      return;
    }
    res.render('index', {
      //temp: data.list[0].main.temp,
      place: body.city['name'] // || data.city['name'],
      //wind: data.list[0].wind.speed,
      //desc: data.list[0].weather[0].description,
    });
  });

})


app.listen(port, () => {
  console.log(`listening on port ${chalk.green(port)}`);
});

如果您在 api 调用完成后尝试渲染。

【讨论】:

  • 我收到回调不是函数错误。回调是在这里使用的最佳选择吗?
  • 已更新。看起来你颠倒了回调参数。当调用它们时,首先使用错误,然后是结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-28
  • 1970-01-01
  • 1970-01-01
  • 2012-05-25
  • 1970-01-01
相关资源
最近更新 更多