![](/img/trans.png)
[英]SyntaxError: JSON.parse: unexpected character at line 3 column 1 of the JSON data
[英]SyntaxError: “JSON.parse: unexpected character at line 1 column 1 of the JSON data” with Fetch api
我正在嘗試使用 Fetch api 將一些帶有 Javascript 的 HTML 表單輸入傳遞到服務器端(Flask)。 當我發送 POST 請求時,它工作正常,我也可以接收數據,但它也在 Mozilla Firefox 上給了我這個錯誤聲明:
SyntaxError:“JSON.parse:JSON 數據的第 1 行第 1 列出現意外字符”
在谷歌瀏覽器上它給了我:
語法錯誤:位置 0 處的 JSON 中出現意外標記 <
這是我的 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)
為什么會這樣? 你能幫我么?
對於故障排除 api,我更喜歡你使用郵遞員。在你的情況下,你的渲染函數傳遞一個不是 json 格式的 html 文件。在燒瓶中,我們使用對象序列化庫將非 json 數據轉換為 json。Marshmallow 是一個 ORM/ODM/框架- 用於將復雜數據類型(例如對象)轉換為本地 Python 數據類型或從本地 Python 數據類型轉換的不可知庫。但在您的情況下,它無濟於事。但是對於您的問題,請查看此博客文章,希望它能有所幫助。 博文
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.