React/JSX未在表单中运行onClick/fetch函数,而是提交到”/”。

huangapple go评论69阅读模式
英文:

React/JSX not running onClick/fetch function in form instead posting to "/"

问题

我尝试在React应用程序中创建一个表单,用于向Flask后端发送POST请求。该请求可以作为URL中的GET请求(默认表单行为)发送,也可以作为POST请求发送到"proxyaddr/"(错误的URL)。

这是表单和发送数据的函数:

import React, { useEffect, useState } from 'react';

export default function PaymentForm() {

    const [startDate, setStartDate] = useState();
    const [endDate, setEndDate] = useState();
    const [frequency, setFrequency] = useState();
    const [payDates, setPayDates] = useState();
    const [isError, setError] = useState(false);

    // 函数 errorMsg({hasError}) 省略
    // 函数 submitData(data) 省略
    // 函数 handPaymentForm(e) 省略

    return (
        <React.Fragment>
        <p className="text-gray-500 font-bold mt-10">Schedule Payments</p>
        <form onSubmit={handPaymentForm}>
            <label>Start Date: <input name="start_date" type="date" onChange={(e)=> setStartDate(e.target.value)}/></label>
            <br/><label>End Date: <input name="end_date" type="date" onChange={(e)=> setEndDate(e.target.value)}/></label>
            <br/><label>
                <select name="frequency" onChange={(e)=> setFrequency(e.target.value)}>
                    <option value="WEEKLY">Weekly</option>
                    <option value="BI-WEEKLY">Bi-Weekly</option>
                    <option value="MONTHLY">Monthly</option>
                    <option value="BI-MONTHLY">Bi-Monthly</option>
                    <option value="QUARTERLY">Quarterly</option>
                    <option value="SEMI-YEARLY">Semi-Yearly</option>
                    <option value="ANNUAL">Annual</option>
                </select>
            </label>
            <br/><button type="submit">Submit</button>
        </form>
        <errorMsg hasError={isError}/>
        </React.Fragment>
    )
}

这是Flask Python文件:

# Flask Python 文件内容省略

来自Flask的输出(前两个是我在表单标签中没有指定action="get/post"时测试的):

127.0.0.1 - - [19/Apr/2023 12:13:03] "POST /?start_date=&end_date=&frequency=WEEKLY HTTP/1.1" 404 -
127.0.0.1 - - [19/Apr/2023 12:18:10] "POST /?start_date=&end_date=&frequency=WEEKLY HTTP/1.1" 404 -
127.0.0.1 - - [19/Apr/2023 12:19:28] "POST / HTTP/1.1" 404 -
127.0.0.1 - - [19/Apr/2023 12:19:45] "POST / HTTP/1.1" 404 -

编辑:我想补充说明一下,我尝试将alert()添加到函数中以确认它是否真正运行,但似乎没有运行。这是我第一次使用Stack Overflow,多年来我已阅读了大量答案,但从未提出过问题。如果我遗漏了一些重要信息,我很抱歉,并愿意添加任何可能有用的信息。我感激任何帮助,我对Web开发还很新。

英文:

I'm trying to make a form in a react app send a post request to a flask backend. The request is either sent as a GET in the URL (default form behavior) or send as a POST to "proxyaddr/" (bad URL)

Here is the form and function to send the data:

import React, { useEffect, useState } from &#39;react&#39;;
export default function PaymentForm() {
const [startDate, setStartDate] = useState();
const [endDate, setEndDate] = useState();
const [frequency, setFrequency] = useState();
const [payDates, setPayDates] = useState();
const [isError, setError] = useState(false);
function errorMsg({hasError}){
if (hasError)
return &lt;p&gt;Error occured&lt;/p&gt;
}
function submitData(data){
fetch(&#39;/get_dates&#39;, {method: &quot;post&quot;, body: data})
.then((responce) =&gt; {
const res = responce.formData
setPayDates(res.get(&quot;frequency_dates&quot;))
})
}
function handPaymentForm(e){
e.preventDefaults();
alert(&quot;ran&quot;);
const form = e.target;
const formData = new FormData(form);
const jsonData = Object.formEntries(formData);
try { 
submitData(jsonData);
}
catch(e){
setError(true);
}
}
return (
&lt;React.Fragment&gt;&lt;p className=&quot;text-gray-500 font-bold mt-10&quot;&gt;Schedule Payments&lt;/p&gt;
&lt;form onSubmit={handPaymentForm}&gt;
&lt;label&gt;Start Date: &lt;input name=&quot;start_date&quot; type=&quot;date&quot; onChange={(e)=&gt; setStartDate(e.target.value)}/&gt;&lt;/label&gt;
&lt;br/&gt;&lt;label&gt;End Date: &lt;input name=&quot;end_date&quot; type=&quot;date&quot; onChange={(e)=&gt; setEndDate(e.target.value)}/&gt;&lt;/label&gt;
&lt;br/&gt;&lt;label&gt;
&lt;select name = &quot;frequency&quot; onChange={(e)=&gt; setFrequency(e.target.value)}&gt;
&lt;option value=&quot;WEEKLY&quot;&gt;Weekly&lt;/option&gt;
&lt;option value=&quot;BI-WEEKLY&quot;&gt;Bi-Weekly&lt;/option&gt;
&lt;option value=&quot;MONTHLY&quot;&gt;Monthly&lt;/option&gt;
&lt;option value=&quot;BI-MONTHLY&quot;&gt;Bi-Monthly&lt;/option&gt;
&lt;option value=&quot;QUARTERLY&quot;&gt;Quarterly&lt;/option&gt;
&lt;option value=&quot;SEMI-YEARLY&quot;&gt;Semi-Yearly&lt;/option&gt;
&lt;option value=&quot;ANNUAL&quot;&gt;Annual&lt;/option&gt;
&lt;/select&gt;
&lt;/label&gt;
&lt;br/&gt;&lt;button type=&quot;submit&quot; &gt;Submit&lt;/button&gt;
&lt;/form&gt;
&lt;errorMsg hasError={isError}/&gt;
&lt;/React.Fragment&gt;
)
}

and here is the flask python file:

from datetime import date, datetime, timedelta
import holidays
from flask import Flask, jsonify, request
from flask_cors import CORS
app = Flask(__name__)
term_dict = {
&quot;WEEKLY&quot;: 7,
&quot;BI-WEEKLY&quot;: 14,
&quot;MONTHLY&quot;: 30,
&quot;BI-MONTHLY&quot;: 60,
&quot;QUARTERLY&quot;: 90,
&quot;SEMI-YEARLY&quot;: 180,
&quot;ANNUAL&quot;: 365
}
@app.get(&#39;/test_endpoint&#39;)
def test_endpoint():
return {&quot;members&quot; : [&quot;1&quot;, &quot;2&quot;,&quot;3&quot;]}
@app.post(&#39;/get_dates&#39;)
def frequency_dates():
data = request.get_json()
print(&quot;hello&quot;)
start_date = datetime.strptime(data[&#39;start_date&#39;], &#39;%Y-%m-%d&#39;).date()
end_date = datetime.strptime(data[&#39;end_date&#39;], &#39;%Y-%m-%d&#39;).date()
term = request.form[&#39;term&#39;]
if term not in term_dict:
return jsonify({&#39;error&#39;: &#39;Bruh invalid term&#39;}), 400
frequency_dates = []
delta_days = term_dict[term]
current_date = start_date
while current_date &lt;= end_date:
frequency_dates.append(str(current_date))
current_date += timedelta(days=delta_days)
return jsonify({&#39;frequency_dates&#39;: frequency_dates}), 200
@app.route(&#39;/is_us_holiday&#39;, methods=[&#39;POST&#39;])
def is_us_holiday():
input_date = datetime.strptime(request.form[&#39;input_date&#39;], &#39;%Y-%m-%d&#39;).date()
us_holidays = holidays.US()
us_holidays = holidays.country_holidays(&#39;US&#39;)
nyse_holidays = holidays.NYSE()
nyse_holidays = holidays.financial_holidays(&#39;NYSE&#39;)
is_holiday = input_date in us_holidays or input_date in nyse_holidays
return jsonify({&#39;is_holiday&#39;: is_holiday}), 200
cors = CORS(app, resources={&#39;/*&#39;:{&#39;origins&#39;: &#39;http://localhost:3000&#39;}}) 
if __name__ == &quot;__main__&quot;:
app.run()

Output from flask (first two are when I tested in with no action="get/post" in the form tag):

127.0.0.1 - - [19/Apr/2023 12:13:03] &quot;POST /?start_date=&amp;end_date=&amp;frequency=WEEKLY HTTP/1.1&quot; 404 -
127.0.0.1 - - [19/Apr/2023 12:18:10] &quot;POST /?start_date=&amp;end_date=&amp;frequency=WEEKLY HTTP/1.1&quot; 404 -
127.0.0.1 - - [19/Apr/2023 12:19:28] &quot;POST / HTTP/1.1&quot; 404 -
127.0.0.1 - - [19/Apr/2023 12:19:45] &quot;POST / HTTP/1.1&quot; 404 -

Edit: I would like to add I tried adding alert() to if the function was actually running and it appears not to.
This is my first time using stack overflow, I've read plenty of answers over the years but never submitted a question. I apologies if I've missed some important information and am happy to add anything which may be of use. I appreciate any assistance, I'm rather new to web development.

答案1

得分: 0

将我的评论发布为回答以增加可见度。

在您的 handPaymentForm 表单提交事件处理程序中,有一个拼写错误:

e.preventDefaults();

事件对象上的方法是 preventDefault()(没有 "s"),因此上面的代码应该改为 e.preventDefault()

英文:

Posting my comment as an answer for visibility.

In your handPaymentForm form submit event handler, there is a typo:

e.preventDefaults();

The method on the event object is preventDefault() (with no "s"), so the above line should just be e.preventDefault() instead.

huangapple
  • 本文由 发表于 2023年4月20日 02:21:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76057716.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定