[英]Specify node-fetch to get JSON
Is there a way to specify node-fetch to request for JSON for a GET request? 有没有一种方法可以指定节点获取以请求GET请求的JSON? The external api endpoint I'm trying to reach sends back xml. 我尝试到达的外部api端点会发回xml。
I know I can do something like this on the front-end, but can I do this in my node-server? 我知道我可以在前端执行类似的操作,但是可以在节点服务器上执行此操作吗?
const response = fetch(url, {
method: 'GET',
headers: {
'Accept': 'application/json',
}
});
server.js server.js
const express = require('express')
const path = require('path')
const bodyParser = require('body-parser')
const fetch = require('node-fetch')
const app = express()
const port = process.env.PORT || 5000
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.get('/buses/location', (req, res) => {
const apiURL = `${TRANSLINK_URL}${TRANSLINK_TOKEN}`
fetch(apiURL)
.then(response => {
if (response.ok) {
response.json()
.then((data) => {
res.json(data)
})
.catch(err => {
console.log(err)
})
}
else {
res.sendStatus(response.status)
}
})
.catch(error => {
console.log(error)
})
})
This code include the application/json request header and it is refactored with async/await , you should use that instead of callbacks 此代码包含application / json请求标头,并使用async / await进行了重构,您应该使用它而不是回调
app.get('/buses/location', async (req, res) => {
const apiURL = `${TRANSLINK_URL}${TRANSLINK_TOKEN}`;
try {
const response = await fetch(apiURL, { headers: { 'Content-Type': 'application/json' }});
const jsonResponse = await response.json();
res.send(jsonResponse);
}
catch (e){
console.log(e);
}
})
However, the server you are reaching must support json responses when requested, otherwise you will have to manage your data as xml 但是,要访问的服务器在请求时必须支持json响应,否则您将不得不将数据作为xml管理
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.