React和axios-发送GET和POST请求而不是仅发送POST

时间:2019-11-09 00:09:47

标签: reactjs request axios

在React中,我正在提交以下表单:

<form onSubmit={ (event) => this.handleSubmitOrder(event) }>
          <div className="field">
             <input
                name="client"
                className="input is-dark is-large"
                type="text"
                placeholder="Client name"
                required
                //value={this.state.formClient.client}
                onChange={this.handleOrderFormChange}
              /> 
          </div>
            <div className="field">
              <input
                name="email"
                className="input is-dark is-large"
                type="text"
                placeholder="Client email"
                required
                //value={this.state.formClient.email}
                onChange={this.handleOrderFormChange}
              />
            </div>
          <input
            type="submit"
            className="button is-dark is-large is-fullwidth"
            value="Submit"
          />
          </form>

这是handleSubmitOrder(),正在处理POST请求:

  handleSubmitOrder(event) {
    const {userId} = this.props
    const data = {
      client: this.state.formClient.client,
      email: this.state.formClient.email,
    };
    var headers = {
        'Content-Type': 'application/json',
        //'Access-Control-Allow-Origin': true,
        Authorization: `Bearer ${window.localStorage.authToken}`
      }
    const url = `${process.env.REACT_APP_WEB_SERVICE_URL}/orders/${userId}`;
    axios.post(url, data, {headers: headers})
      .then((res) => {
        console.log(data);
      })
      .catch((err) => {
      });
  };

我使用nginx作为代理服务器(nginx.conf):

  location /orders {
    proxy_pass        http://web:5000;
    proxy_redirect    default;
    proxy_set_header  Upgrade $http_upgrade;
    proxy_set_header  Connection "upgrade";
    proxy_set_header  Host $host;
    proxy_set_header  X-Real-IP $remote_addr;
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header  X-Forwarded-Host $server_name;
  }

在我的Flask服务器上,我有自己的看法,特别是只声明了POST方法:

@orders_bp.route('/orders/<user_id>', methods=['POST'])
def orders(user_id):
    # business logic
    return jsonify(response_object), 200

可以正常访问此端点,并且/orders处的逻辑已被成功处理。

但是当我提交表单时,我在浏览器中遇到404错误,并且令我感到困惑的是,GET请求:

"GET /orders?client=Ozorio&email=ozo%40gmail.com&phone=118888888&select=pick HTTP/1.0" 404 -

如果有帮助,我还要在此处声明网址:

App.jsx:

<Route exact path='/orders' render={() => (
   <Orders
     formType={'Orders'}
     isAuthenticated={this.state.isAuthenticated}
    />
)} />

在这里,在navbar上,我要求输入网址:

    {props.isAuthenticated &&
   <Link to="/orders" className="navbar-item">Orders</Link>
    }

注意:我已通过身份验证。


这可能是什么问题?

1 个答案:

答案 0 :(得分:1)

默认情况下,表单的行为方式非常有趣。您可以详细了解here

最后,您需要添加

event.preventDefault()

handleSubmitOrder函数顶部的功能(以防止提交表单的默认行为)