简体   繁体   中英

Losing ajax data in Express middleware

I have an Node/Express app that has an authorized user logged in. I then have that user make an ajax call with data to a protected route. I have middleware making sure the user is authenticated before continuing to the route. The data is lost between the ajax call and then hitting the route. Is there a way to preserve the data from being lost in this middleware?

Front end .js file

$.ajax({
  url: "/voted",
  method: "POST",
  data: { item1: "some data", item2: "other data" },
  success: () => { console.log("success") },
  failure: () => { console.log("failure") }
});

middleware for the route

// data being lost here
const protectedMiddleware = (req, res, next) => {

  if (req.isAuthenticated()) {
    next();
  }
  else {
    res.redirect("/login");
  }
}

route in my routes.js file

app.post("/voted", protectedMiddleware, (req, res) => {

  let item1 = req.query.item1;
  let item2 = req.query.item2;
  console.log(item1); // undefined
  console.log(item2); // undefined

});

For item1 and item2, I'm getting undefined, whereas they should be "some data" and "other data".

req.query is set from the query parameters in the url. So, req.query.item1 would be accessible if the request url looked like /voted?item1=somedata .

What you are looking for is req.body , since you are passing your data in the body of the request.

You can access item1 and item2 as req.body.item1 and req.body.item2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM