简体   繁体   中英

SyntaxError: “JSON.parse: unexpected character at line 1 column 1 of the JSON data” with Fetch api

I'm trying to pass some HTML form inputs with Javascript using Fetch api to the server side (Flask). When I send a POST request, it works perfect and I can receive the data as well, but it also gives me this error statement on Mozilla Firefox:

SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"

And on Google Chrome it gives me:

SyntaxError: Unexpected token < in JSON at position 0

Here is my Fetch api code:

$(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();
    }
 });
});

And this is how I receive data on the server side:

@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)

Why is that happening? Can you please help me?

For Troubleshooting api I prefer u to use postman.In your case your rendering function passing a html file which is not in json format.In flask we use object serialization library to convert non json data to json.Marshmallow is an ORM/ODM/framework-agnostic library for converting complex datatypes, such as objects, to and from native Python datatypes.But in ur case it will not help.However for ur problem check this blog post hope it will help. blog post

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM