【问题标题】:How to send array and boolean data in body of POST request of API如何在 API 的 POST 请求正文中发送数组和布尔数据
【发布时间】:2020-09-17 14:32:12
【问题描述】:

如何在 API 的 POST 请求正文中发送数组和布尔数据。 以下是我试图发送数组和布尔数据但它被转换为字符串的代码。

fetch('https://cors-anywhere.herokuapp.com/http://35.153.16.107:8080/restaurant/createProfile',{
        method:'post',
        headers:{Authorization:localStorage.getItem('token'), 'Content-Type':'application/json'},
        body: JSON.stringify({
            route:this.state.route,
            side:this.state.side,
            mustHaveDishes:this.state.mustTryDishes,      //This is array
            preOrderDineIn:this.state.preOrderDineIn,     //This is boolean
            preOrderTakeaway:this.state.preOrderTakeaway, // This is boolean
            veg:this.state.vegOnly                        // This is boolean 
        }),
    })
    .then(response => response.json())
    .then(data =>{
        if(data.statusCode === '2000'){
            console.log(this.state.mobile);
            this.props.onRouteChange('orderar','nav');
        }
        else
         console.log(data.error);
    })

这就是我想要发送数组和布尔数据的方式-

        mustHaveDishes:["paratha"],
        preOrderDineIn:true,
        preOrderTakeaway:true,
        veg:true

【问题讨论】:

    标签: reactjs api rest request fetch-api


    【解决方案1】:

    您认为JSON.stringify 除了获取 JSON 对象并将其转换为字符串之外还做了什么?

    身体应该看起来像

    body: {
      route: this.state.route,
      side: this.state.side,
      mustHaveDishes: this.state.mustTryDishes,
      preOrderDineIn: this.state.preOrderDineIn,
      preOrderTakeaway: this.state.preOrderTakeaway,
      veg: this.state.vegOnly
    },
    

    【讨论】:

    • 那么我将如何将路由和边转换为字符串?
    • 什么是routeside,为什么要转换成字符串?
    • route 将包含两个城市名称 {exp- route: "NewYork-LA"} 将由用户输入,side 是单个城市的名称 {exp- side:"NewYork"}
    • 其实向API发送数据的格式是-route:"New York- LA", side:"New York", mustHaveDishes:["paratha"], preOrderDineIn: true, preOrderTakeaway: true, veg: true
    • 那么,如果 route 和 side 已经是字符串,为什么还要再次对它们进行字符串化?
    猜你喜欢
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多