SyntaxError:获取API时出现意外的输入结尾



我面临一个新问题,这个问题以前在这个链接中被问过。但这与我的问题无关。

我实现的是一个非常简单的API,使用nodejsexpress-frameworkmongoose。问题出在获取API上。我想提交一些ID并将其发布到服务器。在服务器端,我根据用户输入的ID将其重定向到正确的URL。每当我测试这个部件时,这个错误都会在前端出现,并指向return response.json()行。

SyntaxError:输入意外结束

这是我的代码:

前端:

function submitCode(){
var nationalCode = document.getElementById('nationalCode').value
var data = {
nationalCode: nationalCode,
creationDate: new Date().toLocaleDateString()
}
fetch('/submit', {
method: 'POST',
redirect:'manual',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(data)
},
).then(response => {
return response.json()
}).then(jsonData => {
console.log('success:', jsonData)
history.pushState(null, null, "/lashkhor")
}).catch(e => {
console.log('error:', e)
return e
})
}

后端:

app.post('/submit', (req, res) => {
var nationalCode = req.body.nationalCode
var creationDate = req.body.creationDate
query = {'nationalCode': nationalCode}
nationalCodeModel.find(query, (err, success) => {
if (err) {
console.log('error:', err)
}
else if (success.length == 0){
nationalCodeModel.create({
nationalCode: nationalCode,
creationDate: creationDate
})
console.log('salam khoshgele daei!')
res.redirect('/khoshgeledaei')
}
else if (success.length > 0) {
console.log('lashkhor detected')
res.redirect('/lashkhor')
}
})
})
app.get('/lashkhor', (req, res) => {
console.log('here')
res.send('salam')
})

我找不到任何解决问题的线索。如果有人能帮助我,我将不胜感激。

PS:整个代码在此存储库中可用

谢谢!

您正在尝试将文本解析为json。您可以从后端使用res.json()而不是res.send()

最新更新