【问题标题】:SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data" with Fetch apiSyntaxError:“JSON.parse:JSON 数据的第 1 行第 1 列的意外字符”使用 Fetch api
【发布时间】:2020-04-17 16:38:45
【问题描述】:

我正在尝试使用 Fetch api 将一些带有 Javascript 的 HTML 表单输入传递到服务器端(Flask)。当我发送 POST 请求时,它运行良好,我也可以接收数据,但它也在 Mozilla Firefox 上给了我这个错误声明:

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

在谷歌浏览器上它给了我:

SyntaxError: Unexpected token

这是我的 Fetch 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)

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

【问题讨论】:

  • 大部分时间无效字符是< 意味着响应是html。您可以在尝试解析它之前 console.log 值以验证
  • 您的 login() 函数正在渲染 index.html,这可能是 HTML,而不是 JSON。

标签: javascript json forms flask fetch-api


【解决方案1】:

对于 api 故障排除,我更喜欢你使用邮递员。在你的情况下,你的渲染函数传递一个不是 json 格式的 html 文件。在烧瓶中,我们使用对象序列化库将非 json 数据转换为 json.Marshmallow 是一个 ORM/ ODM/框架无关库,用于将复杂数据类型(例如对象)与本机 Python 数据类型相互转换。但在您的情况下,它无济于事。但是对于您的问题,请查看此博客文章,希望它会有所帮助。 blog post

【讨论】:

    猜你喜欢
    • 2016-01-30
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 2021-09-14
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    相关资源
    最近更新 更多