首页 > 解决方案 > 传递路径参数在 URL 调用中返回 object%20Object

问题描述

我正在尝试在 ReactJs 中的 axios 调用中根据我的{accountId}值进行一般 axios 调用,如下所示:

服务工厂.js

const devURl = 'https://localhost:3000/service/';
const authToken = '<some_string>';
const accounts = (event) => (
    (accountId) => (
    axios.get(devURl + `accounts/${accountId}/health`, {
        headers: {
          Authorization: authToken,
        },
    }).then(response => ({ data: response.data })).catch(error => ({ error }))
    )
);

但是当我在我的 componentDidMount() 中调用它时,如下所示:

constructor(props) {
        super(props);
        this.executeService = this.executeService.bind(this)
        this.state = {
             id : 707
        };
    }
componentDidMount() {
        this.Service = ServiceFactory.accounts();
        this.executeService();
    }

executeService() {
        console.log("in execute")
        this.Service({accountId: this.state.id}).then((response) => {
            if (response.data) {
                this.serviceSuccess(response.data);
            } else {
                this.serviceFailure(response.error);
            }
        });
    }

它在我的浏览器中返回这个 URL: https://localhost:3000/service/accounts/[object%20Object]/health

谁能帮助我如何将路径参数正确传递给我的 axios GET() 调用。

标签: reactjsaxios

解决方案


也许您的转译器无法将此行转译为纯字符串代码:

axios.get(devURl + `accounts/${accountId}/health`, {

所以改成:

axios.get(`${devURl}accounts/${accountId}/health`, {

或者

axios.get(devURl + "accounts/" + accountId + "/health", {

推荐阅读