异步代码无法与事件监听器一起使用

*为清楚起见并反映更改进行了编辑:

你好我正在努力理解为什么我的异步函数在单独运行时以及在链接在一起时都能正常工作,而在链接在一起并在事件侦听器中触发时却无法正常工作。...

值得注意的是:当我尝试在没有均匀监听器的情况下运行此程序时,数据从我的应用程序通过我的发布路径传递,并以应有的方式传递到我的端点,然后通过正确的路径返回到我的应用程序,依此类推但是,我在控制台中确实收到一条错误消息:

error SyntaxError: Unexpected token < in JSON at position 0

但是,当我尝试单击dom元素来运行我的异步函数链时,我没有得到以上错误,数据传递到了我的发布路线,我可以记录发布的对象:>

Object: null prototype] { zipcode: '97206',feel: 'confused' }

但是我的服务器没有保存任何数据,并且从未触发我的获取路由,并且没有任何内容发送回我的应用程序.......

我很迷路.....

下面的完整服务器和应用代码:

服务器:


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",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",res) => {
  console.log("getData route was hit,sent: ",projectData)
  res.send(projectData);
})

app.listen(3000,res) => {
  console.log("Listening on port 3000");
});

app

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,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");
//     });
//   });

// });

编辑:

我意识到当事件监听器触发我的异步功能时,通过发布路由传递的信息实际上只是表单输入元素值,而不是获取/发布请求的内容。从表单输入中删除名称属性后,我的发布路线一无所获……但是对应功能在没有事件监听器的情况下也能正常工作。

我很困惑。

yaddchg 回答:异步代码无法与事件监听器一起使用

好吧,在我的发帖请求结果上使用.text()而不是.json()解决了语法错误。

将e.preventDefault()添加为事件监听器回调的第一行,从而修复了事件监听器,现在一切正常。

本文链接:https://www.f2er.com/2805907.html

大家都在问