首页 > 解决方案 > 为什么这个 axios.get 请求不起作用>?

问题描述

我目前正在参加 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) 存在问题。

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

标签: javascriptjsonexpressaxios

解决方案


要获取 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 的响应模式文档


推荐阅读