我开始使用 node.js,并且正在完成一个 ping Accuweather API 并返回 JSON blob 数据的教程。
我几乎明白了......但展示片让我退缩了:
index.js
const express = require('express')
const rp = require('request-promise')
const exphbs = require('express-handlebars')
const path = require('path')
const app = express()
app.engine('.hbs', exphbs({
defaultLayout: 'main',
extname: '.hbs',
layoutsDir: path.join(__dirname, 'views/layouts')
}))
app.set('view engine', '.hbs')
app.set('views', path.join(__dirname, 'views'))
app.get('/:city', (req, res) => {
rp({
uri: 'http://apidev.accuweather.com/locations/v1/search',
qs: {
q: req.params.city,
apiKey: 'hoArfRosT1215'
// Use your accuweather API key here
},
json: true
})
.then((data) => {
console.log(data)
res.render('home', data)
})
.catch((err) => {
console.log(err)
res.render('error')
})
})
app.listen(3000)
主页.hbs
<h2>Success!</h2>
<h2>{{data}}</h2>`
错误.hbs
<h2>Error<h2>
主页.hbs
<html>
<head>
<title>Express handlebars</title>
</head>
<body>
{{{body}}}
</body>
</html>
我用谷歌搜索并没有真正找到一个很好的解决方案。我已经研究了车把的帮助功能......但并没有真正想出任何东西。
我将如何开始显示从 Accuweather API 返回的一些“数据”块?
仅供参考,这是我从控制台返回的 JSON 博客。记录它
[ { Version: 1,
Key: '2156696',
Type: 'City',
Rank: 385,
LocalizedName: 'Providence Forge',
EnglishName: 'Providence Forge',
PrimaryPostalCode: '19468',
Region:
{ ID: 'NAM',
LocalizedName: 'North America',
EnglishName: 'North America' },
Country:
{ ID: 'US',
LocalizedName: 'United States',
EnglishName: 'United States' },
AdministrativeArea:
{ ID: 'PA',
LocalizedName: 'Pennsylvania',
EnglishName: 'Pennsylvania',
Level: 1,
LocalizedType: 'State',
EnglishType: 'State',
CountryID: 'US' },
TimeZone:
{ Code: 'EST',
Name: 'America/New_York',
GmtOffset: -5,
IsDaylightSaving: false,
NextOffsetChange: '2017-03-12T07:00:00Z' },
GeoPosition: { Latitude: 40.18, Longitude: -75.523, Elevation: [Object] },
IsAlias: false,
SupplementalAdminAreas: [ [Object] ],
DataSets: [ 'Alerts', 'ForecastConfidence', 'MinuteCast' ] },
{ Version: 1,
Key: '2172276',
Type: 'City',
Rank: 385,
LocalizedName: 'Providence Forge',
EnglishName: 'Providence Forge',
PrimaryPostalCode: '23140',
Region:
{ ID: 'NAM',
LocalizedName: 'North America',
EnglishName: 'North America' },
Country:
{ ID: 'US',
LocalizedName: 'United States',
EnglishName: 'United States' },
AdministrativeArea:
{ ID: 'VA',
LocalizedName: 'Virginia',
EnglishName: 'Virginia',
Level: 1,
LocalizedType: 'State',
EnglishType: 'State',
CountryID: 'US' },
TimeZone:
{ Code: 'EST',
Name: 'America/New_York',
GmtOffset: -5,
IsDaylightSaving: false,
NextOffsetChange: '2017-03-12T07:00:00Z' },
GeoPosition: { Latitude: 37.442, Longitude: -77.044, Elevation: [Object] },
IsAlias: false,
SupplementalAdminAreas: [ [Object] ],
DataSets: [ 'Alerts', 'ForecastConfidence', 'MinuteCast' ] } ]