1.页面请求
app.get('/list_user', function (req, res) {
console.log("/list_user GET 请求");
//res.send('用户列表页面');
res.send(app.get('env'));
});
成功!
2.get请求
app.get('/index_post', function (req, res) {
res.render('index_post', { title: 'Express' });
});
app.get('/process_get', function (req, res) {
// 输出 JSON 格式
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
});
显示
{"first_name":"1","last_name":"1"}
3.post请求
app.post('/process_post', urlencodedParser, function (req, res) { // 输出 JSON 格式
response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
});
同上。
4.上传文件
app.get('/index_img', function (req, res) {
res.render('index_img', { title: 'Express' });
});
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/file_upload', function (req, res) { console.log(req.files[0]); // 上传的文件信息 var des_file = __dirname + "/" + req.files[0].originalname;
fs.readFile( req.files[0].path, function (err, data) {
fs.writeFile(des_file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'File uploaded successfully',
filename:req.files[0].originalname
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
});
{"message":"File uploaded successfully","filename":"QQ鎴浘20150729155015.png"}
成功
github地址:https://github.com/Wen1750686723/nodejsdemo