英文:
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 '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);
function errorMsg({hasError}){
if (hasError)
return <p>Error occured</p>
}
function submitData(data){
fetch('/get_dates', {method: "post", body: data})
.then((responce) => {
const res = responce.formData
setPayDates(res.get("frequency_dates"))
})
}
function handPaymentForm(e){
e.preventDefaults();
alert("ran");
const form = e.target;
const formData = new FormData(form);
const jsonData = Object.formEntries(formData);
try {
submitData(jsonData);
}
catch(e){
setError(true);
}
}
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>
)
}
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 = {
"WEEKLY": 7,
"BI-WEEKLY": 14,
"MONTHLY": 30,
"BI-MONTHLY": 60,
"QUARTERLY": 90,
"SEMI-YEARLY": 180,
"ANNUAL": 365
}
@app.get('/test_endpoint')
def test_endpoint():
return {"members" : ["1", "2","3"]}
@app.post('/get_dates')
def frequency_dates():
data = request.get_json()
print("hello")
start_date = datetime.strptime(data['start_date'], '%Y-%m-%d').date()
end_date = datetime.strptime(data['end_date'], '%Y-%m-%d').date()
term = request.form['term']
if term not in term_dict:
return jsonify({'error': 'Bruh invalid term'}), 400
frequency_dates = []
delta_days = term_dict[term]
current_date = start_date
while current_date <= end_date:
frequency_dates.append(str(current_date))
current_date += timedelta(days=delta_days)
return jsonify({'frequency_dates': frequency_dates}), 200
@app.route('/is_us_holiday', methods=['POST'])
def is_us_holiday():
input_date = datetime.strptime(request.form['input_date'], '%Y-%m-%d').date()
us_holidays = holidays.US()
us_holidays = holidays.country_holidays('US')
nyse_holidays = holidays.NYSE()
nyse_holidays = holidays.financial_holidays('NYSE')
is_holiday = input_date in us_holidays or input_date in nyse_holidays
return jsonify({'is_holiday': is_holiday}), 200
cors = CORS(app, resources={'/*':{'origins': 'http://localhost:3000'}})
if __name__ == "__main__":
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] "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 -
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论