簡體   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