繁体   English   中英

如何使用node.js在服务器端使用纯JavaScript读取JSON文件?

[英]How to read JSON files with pure javascript on a server side using node.js?

我很少使用Node.js和jQuery,并且一直在寻找解决方案的最后几个小时。 我有一个来自openweathermap.com()的API,该API以JSON格式返回天气信息,而我正在尝试提取温度值。

我正在使用Node.js运行可以从网络上的任何设备访问的程序,并且我以前在客户端上使用jQuery通过$ .getJSON读取文件,但是我正在将我的大部分代码传输到服务器避免需要始终打开浏览器以使程序正常运行。 显然,您不能将jQuery与node.js一起使用,但是我尝试了对node.js的服务器改编,包括cheerio,jsdom和标准的jquery附加组件,但是它们都无法解决问题。 我不能使用XMLHttpRequest或http.get,因为它正在服务器端运行,而我不能简单地使用JSON.parse,因为它是从网站提取的。

如何仅使用纯JavaScript从网站上提取数据,将其存储为对象,然后从中提取数据?

这是我最初在客户端上运行的内容:

  var updateWeather = function(){ $.getJSON('http://api.openweathermap.org/data/2.5/weather?id=5802340&units=imperial&appid=80e9f3ae5074805d4788ec25275ff8a0&units=imperial', function(data) { socket.emit("outsideTemp",data.main.temp); }); } updateWeather(); 
 <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> </head> 

NodeJS本机支持JSON-因此不需要“特殊”工作。 我建议使用像axios这样使我们的生活更轻松的http客户端,但是您可以本机执行此操作。 我在下面提供了两个摘要,供您入门:

使用流行的HTTP客户端

 const axios = require('axios');

axios.get('http://api.openweathermap.org/data/2.5/weather?id=5802340&units=imperial&appid=80e9f3ae5074805d4788ec25275ff8a0&units=imperial').then((res) => {
    console.log(res.data)
})

普通的NodeJS(摘自NodeJS文档

const http = require('http');

http.get('http://api.openweathermap.org/data/2.5/weather?id=5802340&units=imperial&appid=80e9f3ae5074805d4788ec25275ff8a0&units=imperial', (res) => {
  const { statusCode } = res;
  const contentType = res.headers['content-type'];

  let error;
  if (statusCode !== 200) {
    error = new Error('Request Failed.\n' +
                      `Status Code: ${statusCode}`);
  } else if (!/^application\/json/.test(contentType)) {
    error = new Error('Invalid content-type.\n' +
                      `Expected application/json but received ${contentType}`);
  }
  if (error) {
    console.error(error.message);
    // Consume response data to free up memory
    res.resume();
    return;
  }

  res.setEncoding('utf8');
  let rawData = '';
  res.on('data', (chunk) => { rawData += chunk; });
  res.on('end', () => {
    try {
      const parsedData = JSON.parse(rawData);
      console.log(parsedData);
    } catch (e) {
      console.error(e.message);
    }
  });
}).on('error', (e) => {
  console.error(`Got error: ${e.message}`);
});

很多人在节点上使用请求/请求承诺

const req = require('request-promise');

req.get({
    uri: 'http://api.openweathermap.org/data/2.5/weather?id=5802340&units=imperial&appid=80e9f3ae5074805d4788ec25275ff8a0&units=imperial',
    json: true
}).then(e => {console.log(e.coord)});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM