SyntaxError:“ JSON.parse:JSON数据的第1行第1列中的意外字符”,使用Fetch api

问题描述 投票:-1回答:1

我正在尝试使用Fetch api将一些带有Javascript的HTML表单输入传递给服务器端(Flask)。当我发送POST请求时,它可以正常工作,并且我也可以接收数据,但是它在Mozilla Firefox上也显示了此错误声明:

SyntaxError:“ JSON.parse:JSON数据的第1行第1列出现意外字符”

在Google Chrome上,它给了我:

SyntaxError:意外令牌

这是我的提取api代码:

$(document).ready(function() {
    const myForm = document.getElementById("vform");
    myForm.addEventListener('submit', function(e){

    let phonenumber = document.getElementById('phoneNumber').value;
    let password = document.getElementById('password').value;
    let checked = document.getElementById('rememberMe').value;

    if(typeof phonenumber, password, checked !== 'undefined' && phonenumber, password, checked !== null) {

    var data = [{
                    phoneNo: phonenumber,
                    password: password,
                    checked: checked,
                }];

    fetch(`${window.origin}/login`, {
        method:'POST',
        headers: {
            "Content-Type": "application/json" 

        },

        body: JSON.stringify(data)
    })
    .then((res) => res.json())

    .then((data) => console.log(data))

    .catch((err)=>console.log(err))

    e.preventDefault();
    }
 });
});

这就是我在服务器端接收数据的方式:

@app.route("/login", methods=["GET", "POST"])
def login():
  if request.get_json() != None:     
    req = request.json()
    phoneNo = req["phoneNo"]
    password = req["password"]
    checked =  req["checked"]


    print(phoneNo)
    return render_template("index.html", req=req)

为什么会这样?您能帮我吗?

javascript json forms flask fetch-api
1个回答
-2
投票

对于API疑难解答,我更喜欢使用邮递员。在您的情况下,您的呈现函数将传递一个非json格式的html文件。在烧瓶中,我们使用对象序列化库将非json数据转换为json。Marshmallow是ORM / ODM / framework-agnostic库,用于将复杂的数据类型(例如,对象)与本机Python数据类型之间进行转换。但是,在您的情况下,它将无济于事。但是,对于您的问题,请查看此博客文章,希望对您有所帮助。blog post

© www.soinside.com 2019 - 2024. All rights reserved.