首页 > 解决方案 > 无法通过 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
}

标签: node.jstypescriptfetch

解决方案


我觉得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
    }
})


推荐阅读