【问题标题】:How to read JSON files with pure javascript on a server side using node.js?如何使用 node.js 在服务器端使用纯 JavaScript 读取 JSON 文件?
【发布时间】:2023-04-04 06:53:01
【问题描述】:

我几乎没有使用 Node.js 和 jQuery 的经验,过去几个小时一直在寻找解决方案。我有一个来自 openweathermap.com () 的 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>

【问题讨论】:

  • 快速说明...看起来“appid” URL 参数是您的 API 密钥?您可能想从您的问题中编辑它,或者切换到不同的 API 密钥,因为现在有人可能会抓住这个,因为它是公开的。

标签: javascript jquery html node.js json


【解决方案1】:

很多人将request / request promise 与节点一起使用

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)});

【讨论】:

  • 请注意,现在已弃用请求。
  • 是吗? @jonrsharpe 我在 github 上找不到任何通知。换什么?
  • 谢谢!因此,如果我使用它而不是 console.log(e) 我使用类似 var ex = JSON.parse(e);然后是 console.log(ex.main.temp);那行得通吗?
  • 省略 JSON.parse @BradyUnderwood,json:true 已经处理了这个。
【解决方案2】:

NodeJS 本身就支持 JSON——所以不需要“特殊”的工作。我建议使用 http 客户端,它可以让我们的生活更轻松,比如 axios,但您可以在本地执行此操作。我在下面提供了两个 sn-ps 供您开始使用:

使用流行的 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(取自 the NodeJS Docs

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}`);
});

【讨论】:

猜你喜欢
  • 2012-04-18
  • 2016-12-03
  • 1970-01-01
  • 1970-01-01
  • 2011-05-30
  • 1970-01-01
  • 1970-01-01
  • 2017-07-18
  • 2012-11-28
相关资源
最近更新 更多