【问题标题】:How do I get the value I want?如何获得我想要的价值?
【发布时间】:2020-02-11 01:25:18
【问题描述】:

我目前正在做一个 React 项目。 我想通过axios in view将value(1001)发送到服务器,但是服务器没有收到该值。 我需要你的帮助。 谢谢。

------查看文件-------------------------- -----

handleChange(e) {
    //this.setState({option: e.target.value});
    axios
        .get('/status/bus_info',{
            'data': e.target.value
        })
        .then(function(requset) { 
            console.log(requset);
            requset = requset.config.data;
            console.log(requset);
    })
}

render(){
    return(
        <>
        <div className="selwrap floatL">

            <i className="select_icon"><img src={require('img/icon/icon_handle_g.png')} alt="hi"/></i>selectBox
            <select className="transparentInput" value={this.state.option.value} onChange={this.handleChange}>
            {this.state.mariaComData.map((maria, i) => (
                <option id={maria.COMPANY_ID} key={i} value={maria.COMPANY_ID}>{maria.NAME}</option>

            ))}
            </select>
        </div>
        </>
    )
}

------服务器文件-------------------------- -----

router.get('/status/bus_info', (req, res) => {
    //console.log(req.data);
   // res.json(req.data)
    let where = '';

    if(!req)
        where = `where company_id = ${data}`;

    db.query(`select * from myTable${where}`, (err, rows) => {
        if (!err) {
            res.send(rows);
        } else {
            res.send(err);
        }
    });
});

-------------查看console.log------------

{data: Array(26), status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config:
adapter: ƒ xhrAdapter(config)
baseURL: "http://localhost:4000/"
data: "1001"
headers: {Accept: "application/json, text/plain, */*"}
maxContentLength: -1
method: "get"
timeout: 0

【问题讨论】:

  • 如果要向服务器发送数据,请使用 POST 方法。

标签: reactjs express react-router axios router


【解决方案1】:

你必须使用POST HTTP 请求。

根据MDN GETMDN POST

使用GET 的请求应该只检索数据。

HTTP POST 方法向服务器发送数据。

你可以在Axios README找到一个例子

【讨论】:

    【解决方案2】:

    在您的 api 的查询参数中发送您的数据

    axios.get(`/status/bus_info?data:${e.target.value}`)
    .then(function (response) {
    // handle success
    console.log(response);
    })
    .catch(function (error) {
    // handle error
    console.log(error);
    })
    .finally(function () {
    // always executed
    });
    

    在你的 api 中

    router.get('/status/bus_info', (req, res) => {
    const {data} = req.query;
    let where = '';
    
    if(data)
        where = ` where company_id = ${data}`;
    
    db.query(`select * from myTable${where}`, (err, rows) => {
        if (!err) {
            res.send(rows);
        } else {
            res.send(err);
        }
    });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-15
      • 2022-07-31
      • 2021-01-07
      • 1970-01-01
      相关资源
      最近更新 更多