路由总表挂载分表cart
Router.use('/cart', CartRouter)
自动导入第三方模块
const UsersRouter = require('./users')
发送ajax请求
function myAjax5() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "/api/cart/list?current=10086");
xhr.onload = function () {
console.log(JSON.parse(xhr.responseText));
};
xhr.send();
}
myAjax5();
function myAjax6() {
const xhr = new XMLHttpRequest();
xhr.open("POST", "/api/cart/add/?name=老北京卤煮");
xhr.onload = function () {
console.log(JSON.parse(xhr.responseText));
};
xhr.send()
}
myAjax6();
cart.js添加请求原本写法
原本的写法
CartRouter.get("/list", (req, res) => {
res.send({
code: 1,
msg: "请求成功",
tips: `您请求的列表页为 第 ${req.query.current} 页`,
});
});
CartRouter.post('/add', (req, res) => {
res.send({
code: 1,
msg: "请求成功",
tips: `您要添加的商品名为: ${req.body.name}`,
});
})
动态路由写法
// 动态路由的写法
CartRouter.get("/list/:current", (req, res) => {
/**
* 如果是动态路由的写法, 参数就不会放在 req.query
*
* 而是放在 req.params (post 与 get 都一样)
*/
res.send({
code: 1,
msg: "请求成功",
tips: `您请求的列表页为 第 ${req.params.current} 页`,
});
});
CartRouter.post('/add/:name', (req, res) => {
res.send({
code: 1,
msg: "请求成功",
tips: `您要添加的商品名为: ${req.params.name}`,
});
})
修改ajax请求
function myAjax5() {
const xhr = new XMLHttpRequest();
// xhr.open("GET", "/api/cart/list?current=10086");
xhr.open("GET", "/api/cart/list/10086");
xhr.onload = function () {
console.log(JSON.parse(xhr.responseText));
};
xhr.send();
}
myAjax5();
function myAjax6() {
const xhr = new XMLHttpRequest();
// xhr.open("POST", "/api/cart/add/?name=老北京卤煮");
xhr.open("POST", "/api/cart/add/老北京卤煮");
xhr.onload = function () {
console.log(JSON.parse(xhr.responseText));
};
xhr.send()
}
myAjax6();