我有一个函数,handlesubmit,它将一些数据从表单发送到我的后端/
handleSubmit(event){
let username = window.sessionStorage.getItem("username")
console.log(username) //if this line of code is present, or anything else reads username or other session storage, the code fails.
//alert(body)
//alert(username)
fetch("http://localhost:3000/write/", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:3000/write/"
},
body: JSON.stringify({fuck: "fuck"})
}).then(
function(response){
alert("Huh?")
}
)
}
值得注意的是,我已经测试过将用户名发送到后端。它在前端失败,但实际上仍然将用户名发送到 API 。
handleSubmit(event){
let username = window.sessionStorage.getItem("username")
//console.log(username) by removing this line of code, I no longer get the error.
//alert(body)
//alert(username)
fetch("http://localhost:3000/write/", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:3000/write/"
},
body: JSON.stringify({fuck: "fuck"})
}).then(
function(response){
alert("Huh?")
}
)
}
我的API如果有帮助的话。
app.post("/write/", async function(req, res) {
console.log(req["body"])
res.status(200).json(
{message: "test"}
)
})
每当我删除
console.log(username)
时,获取都会起作用。据我所知,用户名并不是未定义的,如果我将其包含在正文中,它确实会到达我的后端。为什么会出现 Failed to Fetch 错误?
在意识到我忘记添加 event.preventDefault() 后,我放弃了程序员的身份,并选择从事腰带制作和猛犸象狩猎。