有没有办法为GET请求指定node-fetch来请求JSON?我试图到达的外部api端点发送回xml。
我知道我可以在前端做这样的事情,但是我能在我的节点服务器中做这件事吗?
const response = fetch(url, {
method: 'GET',
headers: {
'Accept': 'application/json',
}
});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)
})
})发布于 2019-09-14 22:49:21
这段代码包含了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);
}
})但是,当请求时,您要访问的服务器必须支持json响应,否则您将不得不以xml格式管理数据。
https://stackoverflow.com/questions/57926962
复制相似问题