我有一个字典values
,其中包含三个变量:firm
,infosys
,spot
。使用POST
时,我可以在ReactJS中的JSON.stringify({values: values})
请求中使用axios。但是,如果我删除JSON.stringify()
,则会在控制台中看到:
Access to XMLHttpRequest at 'http://127.0.0.1:5000/form/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
此外,当我在axios中使用JSON.stringify({values: values})
以将POST
的值添加到Flask时。返回ImmutableMutliDict
时得到request.form
。我可以在Python中使用request.form
来转换.to_dict()
,但这并不理想。我需要接收实际的JSON数据。
目前,我可以获得的request.form
的最佳结果是:
{'{"values":{"firm":"","infosys":"","spot":""}}': u''}
bp = Blueprint('spot_search', __name__, url_prefix='/')
bp.config = {} # avoids no config error for CORS
CORS(bp, resources={r"/*": {"origins": "*"}})
@bp.route('form/', methods=('GET', 'POST'))
@cross_origin()
def jsonForm():
spotDictionary = current_app.config['SPOTDICTIONARY'] # current_app.config['SPOTDICTIONARY'] is defined in __init__.py. it references spotDictionary.py
# firmList = sorted([(i, i) for i in spotDictionary.keys()])
firmList = sorted([i for i in spotDictionary.keys()])
if request.method == 'GET':
return jsonify(firmList)
elif request.method == 'POST': # break this down by form that gets submitted onchange in react.
data = request.form.to_dict()
current_app.config['LOGGER'].info(data)
try:
current_app.config['LOGGER'].info(data)
except KeyError as e:
current_app.config['LOGGER'].info(e)
resp = make_response('RESPONSE')
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
在React中:
useEffect(() => {
console.log(values);
const postData = async () => {
const data = {values: values}
const result = await axios.post('http://127.0.0.1:5000/form/', data)
console.log(result);
};
postData()
}, [values]);
function handleChange(event) {
setValues({
firm: event.target.value
})
}
const selectOptions = choices.map((choice, index) =>
<MenuItem key={index} value={choice} primarytext={choice}>{choice}</MenuItem>
)
return (
<form className={classes.root} autoComplete="off">
<FormControl className={classes.formControl}>
<InputLabel htmlFor="firm-helper">Firm</InputLabel>
<Select
value={values.firm}
onChange={handleChange}
input={<Input name="firm" id="firm-helper" />}
>
{selectOptions}
</Select>
<FormHelperText>Select a Firm</FormHelperText>
</FormControl>
</form>
)