我有一个项目在线商店。你可以帮助我。当用户点击butt.on时,jquery必须发送ajax请求并将产品ID发送到/ cart路由。邮政请求应检查cookie,如果用户有cookie,则将数据添加到“订单”集合中。但是在serverjs上的post请求不起作用这里是代码: server.js:
var express = require('express');
var app = express();
var ejs = require('ejs');
var _= require('underscore');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
app.use(cookieParser());
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: false}));
/*-----------------------------------------------------------------------------*/
MongoClient.connect('mongodb://localhost:27017/shop', function(err,db){
app.get('/', function(req,res){
db.collection('products').find().toArray(function(err, products){
if(err){
console.log('err');
return;
}
res.render('mainpage',{
products:products
});
});
})
app.get('/products/:id', function(req,res){
db.collection('products').find({_id: new mongo.ObjectId(req.params.id)}).toArray(function(err, product){
if(err){
console.log('err');
return;
}
res.render('products',{
product:product[0]
});
});
})
app.post('/cart', function(req, res){
var cooks = req.cookies.user;
if(!cooks){
var time = new Date().getTime();
return res.cookie('user', time);
}
var data = req.body.data;
db.collection('orders').insertOne({"user": req.cookies, "products":[data]} ,function(err){
if(err){
console.log('err', err);
}
else{
console.log('success');
}
res.end();
});
});
app.get('/cart', function(req, res){
db.collection('orders').find().toArray(function(err, products){
if(err){
console.log('err');
return;
}
res.render('order',{
products:products
});
});
})
});
app.listen(3000);
Jquery的:
$(function(){
$('.btn-default').on('click',function(e){
e.preventDefault();
var data = $(this).data('id');
$.ajax({
url:'/cart',
method:'post',
data:{
'data':data
},
success:function(){
console.log('Added!');
},
error:function(){
}
})
})
})
这里有一小段html:
<p><a class="btn btn-default btn-warning" href="#" role="button" data-id="<%=product._id%>">Add to cart»</a></p>