【问题标题】:Why is this axios.get request not working>?为什么这个 axios.get 请求不起作用>?
【发布时间】:2020-10-15 03:15:20
【问题描述】:

我目前正在参加 Colt Steele 的 Web 开发人员训练营,并且遇到了这个问题...

在这个特定的教程中,我们使用 axios,因为“请求”已经停止,所以我试图遵循这个。

我想要做的是为“/results”页面设置一个 Get 路由,在此我想从 OMDB 电影数据库中提取信息,现在,当我进入这个 Url 时,只需显示 JSON 文件。

我确信有一个明显的解决方案,但在搜索了几个小时后我似乎无法弄清楚。

这是我的代码;

const express = require('express');
const app = express();
const axios = require('axios').default;


app.listen(3000, () => {
    console.log('Im listening');
});

app.get('/results', (req, res) => {
    axios.get('http://www.omdbapi.com/?t=california&apikey=thewdb')
        .then((response) => {
            res.send(response);
        }).catch((err) => {
            console.log('This isnt right');
        })

});

如您所见,我也在使用 express,一切都已正确安装。事实上,当我像这样执行 console.log(response) 时:

axios.get('http://www.omdbapi.com/?t=california&apikey=thewdb')
        .then((response) => {
            console.log(response);
        }).catch((err) => {
            console.log('This isnt right');
        })

它有效,我可以在控制台中看到 API JSON,这让我觉得在 promise 中使用 res.send(response) 存在问题。

任何帮助将不胜感激。抱歉,如果我错过了任何信息,对此还是很陌生...

【问题讨论】:

  • 不知道为什么要这样做,但是我认为如果您使用 axios 库创建一个客户端类并返回结果而不是您这样做的方式会更好。

标签: javascript json express axios


【解决方案1】:

要获取 OMDb 请求的响应数据,请使用 data 属性:

app.get('/', function (req, res, next) {
    axios.get('http://www.omdbapi.com/?t=california&apikey=thewdb')
        .then(result => res.send(result.data))
        .catch(err => res.send(err));
});

有关详细信息,请参阅Axios's Response Schema documentation

【讨论】:

  • 非常感谢@macborowy,超快速的响应和工作享受。非常感谢。
猜你喜欢
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
  • 2018-04-10
  • 2019-10-26
  • 2015-04-11
  • 2020-02-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多