node.js - 无法通过 fetch (express) 获取 api 结果
问题描述
我尝试使用 express 获取 api。但是,我不知道为什么 app.get 不能得到任何结果。在浏览器中,我必须这么久......仍然没有得到任何结果。
但是,我在邮递员上运行 api 链接,它对我来说很好。我想念一切吗??
import * as express from 'express'
import {Request, Response} from 'express'
import * as bodyParser from 'body-parser'
import * as path from 'path';
import fetch from 'node-fetch';
const app = express();
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
const PORT = 8080
app.listen(PORT, ()=>{
console.log('listening to PORT 8080 ')
})
app.get('/', async function(req:Request,res:Response){
try{
await getResidentialData()
}catch(e){
console.log("error")
}
})
async function getResidentialData(){
const res = await fetch('https://api.coinbase.com/v2/currencies')
const result = await res.text();
return result
}
解决方案
我觉得app.get
没有返回任何东西,因为它没有返回任何东西response
。要发回响应,最好res
在 API 调用中使用对象,如下所示:
app.get('/', async function(req:Request,res:Response){
try{
const result = await getResidentialData()
res.status(200).send(result) //<----- add this
}catch(e){
console.log("error")
res.status(400).send("Something went wrong") //<----- add this
}
})
推荐阅读
- autohotkey - 如何设置由鼠标位置触发的按键?
- javascript - 在本地将 Firestore 子集合导出为 CSV 或 JSON
- java - 页面对象模型类中的 NullPointerException
- python - Pandas 数据框将日期从 int64 更改为 datetime 中的日期
- linux - 即使登录有效,Pam_unix sshd 身份验证失败?
- php - 将运输标签打印到热敏打印机
- docker - 使用 docker 在 tensorflow 上调试的简单方法是什么?
- json - 使用代号一显示图像
- c# - if else condition in asp.net
- python - 创建文本图层 psd