【问题标题】:Getting a bad request response from an api call that is supposed to return a link to be used for iframe src从应该返回用于 iframe src 的链接的 api 调用获得错误的请求响应
【发布时间】:2021-11-09 05:52:27
【问题描述】:

我正在尝试使用 GET 方法,以便我可以取回要在 iframe 的 src 属性中使用的链接。所以我做了以下事情:

import axios from 'axios';
import { BASE_API_ROOT } from '../../apiConfig';

async function getJobView() {
  const options = {
    method: 'GET',
    headers: {
      'content-type': 'application/json'
    },
    url: `${BASE_API_ROOT}/level2`
  };

  return axios(options);
}

export { getJobView };

所以我尝试将 iframe 嵌入到弹出模式中。所以我所做的是导入该 api 函数并在我的组件中使用它,如下所示:

  modalContent = () => {
    const { classes, history } = this.props;

    const srcUrl = getJobView().then(res => console.log(res)).catch(err => console.log(err.message));
    console.log(srcUrl);
    const renderGetJobView = () => {
      return <iframe src={srcUrl} style={{ width: '800px', height: '800px' }}></iframe>
    }
    return (
      <Paper className={classes.modalPaper}>
        {renderGetJobView()}
      </Paper>
    );
  };

在控制台中我看到:

对此有什么想法吗?

【问题讨论】:

  • 这意味着,您从响应中得到 404。检查您的服务器是否有任何问题。
  • 404 是“未找到”错误,表示您请求的 api url 不存在。检查您的 api 端点并查看您的 url '${BASE_API_ROOT}/level2' 是否存在。错误消息似乎是结构化的,因此可能有一种方法可以在您的后端跟踪错误。

标签: javascript reactjs api iframe axios


【解决方案1】:

我宁愿以更易读的方式格式化您的代码,并尝试找出它在哪里中断。

axios.js

import axios from 'axios';
import { BASE_API_ROOT } from '../../apiConfig';

const axiosInstance = axios.create({
    baseURL: BASE_API_ROOT,
    headers: {
        'content-type': 'application/json'
    },
})

export const getJobView = async () => {
    return axiosInstance.get("/level2")
}

component.js

const modalContent = () => {
    const { classes, history } = this.props;
    const [srcUrl, setSrcUrl] = useState("")

    useEffect(() => {
        const getJobViewData = async () => {
            try {
                const getJobViewResponse = await getJobView()
                setSrcUrl(getJobViewResponse.data)
            } catch (error) {
                setSrcUrl("")
            }
        }
        getJobViewData()
    }, [])
    return (
        <Paper className={classes.modalPaper}>
            {srcUrl !== ""
                ? <iframe src={srcUrl} style={{ width: '800px', height: '800px' }}></iframe>
                : null
            }
        </Paper>
    );
};

现在,很容易找出代码中断的地方,无论是在 Api 端点还是其他地方。

【讨论】:

    【解决方案2】:

    未找到请求的资源。

    404 状态码表示resource not found。检查您的server 一边您调用正确的API 的URL

    这里可以查看APIapi_response_codes的状态码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-18
      • 1970-01-01
      • 2012-05-05
      • 2013-08-02
      相关资源
      最近更新 更多