【发布时间】:2020-04-25 18:38:08
【问题描述】:
*为清晰起见并反映变化而进行了编辑:
你好。我很难理解为什么我的异步函数单独工作得很好,当链接在一起时,但不是当链接在一起并在事件侦听器中触发时......
值得注意的是:当我尝试在没有监听器的情况下运行它时,数据会从我的应用程序通过我的发布路由并以应有的方式传递到我的端点,然后通过正确的路由等返回到我的应用程序. 但是,我确实在控制台中收到错误消息:
error SyntaxError: Unexpected token < in JSON at position 0
但是,当我尝试在单击 dom 元素时运行我的异步函数链时,我没有收到上述错误,数据被传递到我的发布路线,我可以记录发布的对象:
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 请求的内容。在我从表单输入中删除名称属性后,我根本没有收到任何数据命中我的发布路线......但是,对应的函数在事件侦听器中没有正常工作。
我被难住了。
【问题讨论】:
-
您是否收到错误消息?如果是这样,请将其作为您问题的一部分发布。如果您没有收到错误消息,请尝试将诊断日志记录添加到您的代码中,以确保事情在您期望的时候触发。
-
我在不使用事件侦听器时收到此错误代码,(但是,这是数据实际到达我的发布路由并被保存并记录到控制台的时候) SyntaxError: Unexpected token
标签: node.js express asynchronous fetch es6-promise