Javascript SyntaxError:“;JSON.parse:JSON数据第1行第1列的意外字符;使用fetchapi
我正在尝试使用fetchapi将一些带有Javascript的HTML表单输入传递到服务器端(Flask)。当我发送POST请求时,它工作正常,我也可以接收数据,但它在Mozilla Firefox上也给了我以下错误声明: SyntaxError:“JSON.parse:JSON数据的第1行第1列出现意外字符” 在Google Chrome上,它给了我: SyntaxError:JSON中位置0处出现意外标记< 以下是我的获取api代码:Javascript SyntaxError:“;JSON.parse:JSON数据第1行第1列的意外字符;使用fetchapi,javascript,json,forms,flask,fetch-api,Javascript,Json,Forms,Flask,Fetch Api,我正在尝试使用fetchapi将一些带有Javascript的HTML表单输入传递到服务器端(Flask)。当我发送POST请求时,它工作正常,我也可以接收数据,但它在Mozilla Firefox上也给了我以下错误声明: SyntaxError:“JSON.parse:JSON数据的第1行第1列出现意外字符” 在Google Chrome上,它给了我: SyntaxError:JSON中位置0处出现意外标记
$(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)
为什么会这样?您能帮助我吗?对于api疑难解答,我希望您使用postman。在您的情况下,您的呈现函数传递的html文件不是json格式。在flask中,我们使用对象序列化库将非json数据转换为json。Marshmallow是一个ORM/ODM/框架无关库,用于转换复杂的数据类型,例如对象,本机Python数据类型之间的通信。但对于您的情况,这不会有帮助。但是,对于您的问题,请查看此博客文章,希望它能有所帮助。
大多数情况下,无效字符是
您的login()
函数正在呈现index.html
,这可能是html,而不是JSON。