【问题标题】:Pass id parameter in fetch query (ReactJS)在获取查询中传递 id 参数(ReactJS)
【发布时间】:2020-05-31 21:32:32
【问题描述】:

我是 javscript 开发新手,在查询 URL 中传递 id 参数时遇到了一些问题。 我现在在 body 中传递 ID 值,这是不对的,我猜是 REST 方法。

如何将Id: event.target.DepartmentId.value, 传递到像https://localhost:5001/api/departments/{id} 这样的URL 中?

handleSubmit(event){
    event.preventDefault();
    fetch("https://localhost:5001/api/departments/", {
        method: "PUT",
        headers:{
            "Accept":"application/json",
            "Content-Type":"application/json",
            "Origin": "*"
        },
        body: JSON.stringify({
            Id: event.target.DepartmentId.value,
            Name: event.target.DepartmentName.value
        })
    })
    .then(res=>res.json())
    .then((result)=>
    {
        this.setState({snackbaropen: true, snackbarmsg: "Edited successfully!"})
        
    },
    (error) =>{
        this.setState({snackbaropen: true, snackbarmsg: "failed"})
    }
    )
}

感谢您的帮助!

【问题讨论】:

标签: javascript reactjs fetch-api


【解决方案1】:

你应该使用参数

并在服务器端查询参数

   `https://localhost:5001/api/departments/?id=${id}`

【讨论】:

    【解决方案2】:

    你可以像这样使用 js 模板字面量:

    handleSubmit(event){
        event.preventDefault();
        fetch(`https://localhost:5001/api/departments/${event.target.DepartmentId.value}`, {
            method: "PUT",
            headers:{
                "Accept":"application/json",
                "Content-Type":"application/json",
                "Origin": "*"
            },
            body: JSON.stringify({
                Id: event.target.DepartmentId.value,
                Name: event.target.DepartmentName.value
            })
        })
        .then(res=>res.json())
        .then((result)=>
        {
            this.setState({snackbaropen: true, snackbarmsg: "Edited successfully!"})
            
        },
        (error) =>{
            this.setState({snackbaropen: true, snackbarmsg: "failed"})
        }
        )
    }

    【讨论】:

      【解决方案3】:

      这行得通。而文字没有。

        localhost:5001/api/departments" + event.target.DepartmentId.value
      

      【讨论】:

        猜你喜欢
        • 2020-10-20
        • 2019-09-11
        • 2014-10-22
        • 2018-06-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-25
        相关资源
        最近更新 更多