Express Session ไม่บันทึกเมื่อใช้ $.ajax({});

ตรงตามที่บอกเลย ฉันกำลังพยายามบันทึกข้อมูลบางส่วนในเซสชัน Express และดูเหมือนว่า Express จะถือว่าคำขอ AJAX แต่ละรายการเป็นเซสชันแยกกัน ดังนั้นจึงไม่บันทึกข้อมูลของฉัน

บนไคลเอนต์

$.ajax({
  url: '/orders',
  method: 'post',
  data: { item: item }
});

บนเซิร์ฟเวอร์

router.post('/orders', function(req, res) {
  var sess = req.session,
      order = sess.order || [],
      item = req.body.item || '',
      quantity = req.body.quantity || 1;

  if (!item) return res.status(404).end();

  if (order[item]) {
    order[item] += quantity;
  } else {
    order[item] = quantity;
  }

  //save our order to the session
  req.session.order = order;
  req.session.save();
  console.log(req.session.order); // verified that req.session.order is set

  return res.status(200).end();
});

นี่ไม่ใช่คำขอ CORS - ฉันเองที่เข้าถึงเซิร์ฟเวอร์ในเครื่องของฉันจากไคลเอนต์ที่ทำงานในเครื่อง


person sent1nel    schedule 15.01.2015    source แหล่งที่มา
comment
คุณมี .success โทรกลับไหม?   -  person scniro    schedule 15.01.2015
comment
ฉันไม่เชื่อว่าสิ่งนั้นสำคัญ แต่ถึงแม้ฉันจะมีสิ่งหนึ่งพฤติกรรมก็ยังเหมือนเดิม   -  person sent1nel    schedule 15.01.2015
comment
ฉันเชื่อว่าควรส่งสตริงเซสชันพร้อมกับคำขอ ajax ไปยังเซิร์ฟเวอร์ ตัวอย่างเช่น ในส่วนหัวของคุกกี้ HTTP ใช่ไหม? บางครั้งคำขอ AJAX จะใช้ได้กับส่วนขยายบุรุษไปรษณีย์แต่ไม่อยู่ในแอปพลิเคชัน ลองใช้บุรุษไปรษณีย์ได้ไหม   -  person Daniel Kmak    schedule 15.01.2015
comment
สิ่งที่น่าสนใจก็คือ หากคุณประเภทตัวแปรเซสชันเป็นอาร์เรย์ ก็จะไม่บันทึกเนื้อหา สิ่งที่ฉันต้องทำคือตั้งค่าเปลี่ยน order = sess.order || [] เป็น order = sess.order || {}   -  person sent1nel    schedule 15.01.2015
comment
คุณมีคุกกี้ connection.sid ในฝั่งไคลเอ็นต์ของคุณหรือไม่   -  person Sergio Ivanuzzo    schedule 25.10.2016


คำตอบ (2)


การเพิ่มโค้ดด้านล่างในการกำหนดค่า $.ajax ของคุณอาจช่วยแก้ปัญหาได้:

$.ajax({
  xhrFields: {
    withCredentials: true
  },
  ... // other settings
})
person Sergio Ivanuzzo    schedule 25.10.2016

การใช้การดึงข้อมูลได้ผลสำหรับฉันเหมือนด้านล่าง

fetch(url, { credentials: 'include',
             method: 'post',
             ...// other fetch configs
}).then(onsuccesscallback)

สิ่งสำคัญคือการรวมข้อมูลประจำตัวเมื่อกำหนดค่าการดึงข้อมูล

person njmwas    schedule 06.05.2017