异步代码不适用于事件侦听器
asynchronous code not working with event listener
*为清晰起见并反映更改进行了编辑:
您好。我很难理解为什么我的异步函数单独运行时工作得很好,当链接在一起时,但当链接在一起并在事件侦听器中触发时却不行....
值得注意:当我尝试 运行 这没有一个均匀的监听器时,数据从我的应用程序传递,通过我的 post 路由,并以它应该的方式到达我的端点,然后通过正确的路线等返回到我的应用程序。但是,我确实在控制台中收到一条错误消息:
error SyntaxError: Unexpected token < in JSON at position 0
然而,当我尝试通过单击 dom 元素来 运行 我的异步函数链时,我没有收到上述错误,数据被传递到我的 post 路线,我可以记录 posted 的对象:
Object: null prototype] { zipcode: '97206', feel: 'confused' }
但是我的服务器没有保存任何数据,我的 get 路由也没有被触发,也没有任何东西被发送回我的应用......
我迷路了.....
下面是完整的服务器和应用程序代码:
服务器:
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
app.use(express.static('public'));
//test values
let projectData = {
date: "today",
temp: "38",
feelings: "confused"
};
app.get("/", (req, res) => {
});
app.post("/postData", (req, res) => {
console.log(req.body)
projectData = {
date: req.body.date,
temp: req.body.temp,
feelings: req.body.feelings
}
console.log("post route was hit, saved:", projectData);
res.redirect("/")
});
app.get("/getData", (req, res) => {
console.log("getData route was hit, sent: ", projectData)
res.send(projectData);
})
app.listen(3000, (req, res) => {
console.log("Listening on port 3000");
});
应用程序
let newDate = getDate();
const apiKey = "5fd7b3a253e67a551e88ff34a92b9e02";
const baseURL = "http://api.openweathermap.org/data/2.5/weather?";
// zip=${}&APPID=${}&units=metric;
const userData = {};
// returns the date //
function getDate() {
let d = new Date();
let newDate = d.getMonth() + "." + d.getDate() + "." + d.getFullYear();
return newDate;
}
//constructs string for api call, adds temp to userData object
const getData = async (apiUrl, zip, key) => {
const url = `${apiUrl}zip=${zip}&APPID=${key}&units=metric`;
const result = await fetch(url);
try {
let newData = await result.json()
// console.log(newData.main.temp)
userData.temp = newData.main.temp
}catch(error) {
console.log("error", error);
}
}
// getData(baseURL, 97206, apiKey)
// .then(result => {
// console.log(userData)
// })
//saves contents of userData Object to server
const postData = async (url, data) => {
const result = await fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-type": "application/json"
},
body: JSON.stringify(data)
});
try {
const newData = await result.json();
// console.log(newData);
return newData;
} catch (error) {
console.log("error", error);
}
};
// postData('/postData', userData);
//updates interface with projectData values from server
const updateUI = async url => {
const result = await fetch(url);
try {
const newData = await result.json();
document.getElementById("date").innerHTML = newData.date;
document.getElementById("temp").innerHTML = newData.temp;
document.getElementById("feelings").innerHTML = newData.feelings;
} catch (error) {
console.log("error", error);
}
};
// updateUI("/getData")
// THIS WORKS
userData.date = newDate;
userData.feelings = document.getElementById("feel").value;
const zipCode = document.getElementById("zipcode").value;
getData(baseURL, 97206, apiKey).then(result => {
postData("/postData", userData).then(result => {
updateUI("/getData");
});
});
// THIS DOESNT WORK
// document.getElementById("btn").addEventListener("click", e => {
// userData.date = newDate;
// userData.feelings = document.getElementById("feel").value;
// const zipCode = document.getElementById("zipcode").value;
// getData(baseURL, zipCode, apiKey).then(result => {
// postData("/postData", userData).then(result => {
// updateUI("/getData");
// });
// });
// });
编辑:
我意识到,当我的异步函数被事件监听器触发时,通过 post 路由传递的信息实际上只是表单输入元素值,而不是 fetch/post 请求。在我从表单输入中删除 name 属性后,我在 post 路由上根本没有得到任何数据……但是,在不在事件监听器中的情况下,corosponding 函数工作正常。
我被难住了。
好吧,在我的 post 请求的结果中使用 .text() 而不是 .json() 解决了语法错误。
添加 e.preventDefault() 作为我的事件侦听器回调的第一行修复了事件侦听器,现在一切正常。
*为清晰起见并反映更改进行了编辑:
您好。我很难理解为什么我的异步函数单独运行时工作得很好,当链接在一起时,但当链接在一起并在事件侦听器中触发时却不行....
值得注意:当我尝试 运行 这没有一个均匀的监听器时,数据从我的应用程序传递,通过我的 post 路由,并以它应该的方式到达我的端点,然后通过正确的路线等返回到我的应用程序。但是,我确实在控制台中收到一条错误消息:
error SyntaxError: Unexpected token < in JSON at position 0
然而,当我尝试通过单击 dom 元素来 运行 我的异步函数链时,我没有收到上述错误,数据被传递到我的 post 路线,我可以记录 posted 的对象:
Object: null prototype] { zipcode: '97206', feel: 'confused' }
但是我的服务器没有保存任何数据,我的 get 路由也没有被触发,也没有任何东西被发送回我的应用......
我迷路了.....
下面是完整的服务器和应用程序代码:
服务器:
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
app.use(express.static('public'));
//test values
let projectData = {
date: "today",
temp: "38",
feelings: "confused"
};
app.get("/", (req, res) => {
});
app.post("/postData", (req, res) => {
console.log(req.body)
projectData = {
date: req.body.date,
temp: req.body.temp,
feelings: req.body.feelings
}
console.log("post route was hit, saved:", projectData);
res.redirect("/")
});
app.get("/getData", (req, res) => {
console.log("getData route was hit, sent: ", projectData)
res.send(projectData);
})
app.listen(3000, (req, res) => {
console.log("Listening on port 3000");
});
应用程序
let newDate = getDate();
const apiKey = "5fd7b3a253e67a551e88ff34a92b9e02";
const baseURL = "http://api.openweathermap.org/data/2.5/weather?";
// zip=${}&APPID=${}&units=metric;
const userData = {};
// returns the date //
function getDate() {
let d = new Date();
let newDate = d.getMonth() + "." + d.getDate() + "." + d.getFullYear();
return newDate;
}
//constructs string for api call, adds temp to userData object
const getData = async (apiUrl, zip, key) => {
const url = `${apiUrl}zip=${zip}&APPID=${key}&units=metric`;
const result = await fetch(url);
try {
let newData = await result.json()
// console.log(newData.main.temp)
userData.temp = newData.main.temp
}catch(error) {
console.log("error", error);
}
}
// getData(baseURL, 97206, apiKey)
// .then(result => {
// console.log(userData)
// })
//saves contents of userData Object to server
const postData = async (url, data) => {
const result = await fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-type": "application/json"
},
body: JSON.stringify(data)
});
try {
const newData = await result.json();
// console.log(newData);
return newData;
} catch (error) {
console.log("error", error);
}
};
// postData('/postData', userData);
//updates interface with projectData values from server
const updateUI = async url => {
const result = await fetch(url);
try {
const newData = await result.json();
document.getElementById("date").innerHTML = newData.date;
document.getElementById("temp").innerHTML = newData.temp;
document.getElementById("feelings").innerHTML = newData.feelings;
} catch (error) {
console.log("error", error);
}
};
// updateUI("/getData")
// THIS WORKS
userData.date = newDate;
userData.feelings = document.getElementById("feel").value;
const zipCode = document.getElementById("zipcode").value;
getData(baseURL, 97206, apiKey).then(result => {
postData("/postData", userData).then(result => {
updateUI("/getData");
});
});
// THIS DOESNT WORK
// document.getElementById("btn").addEventListener("click", e => {
// userData.date = newDate;
// userData.feelings = document.getElementById("feel").value;
// const zipCode = document.getElementById("zipcode").value;
// getData(baseURL, zipCode, apiKey).then(result => {
// postData("/postData", userData).then(result => {
// updateUI("/getData");
// });
// });
// });
编辑:
我意识到,当我的异步函数被事件监听器触发时,通过 post 路由传递的信息实际上只是表单输入元素值,而不是 fetch/post 请求。在我从表单输入中删除 name 属性后,我在 post 路由上根本没有得到任何数据……但是,在不在事件监听器中的情况下,corosponding 函数工作正常。
我被难住了。
好吧,在我的 post 请求的结果中使用 .text() 而不是 .json() 解决了语法错误。
添加 e.preventDefault() 作为我的事件侦听器回调的第一行修复了事件侦听器,现在一切正常。