目录:
node01-创建服务器
node02-util
node03-events
node04-buffer
node05-fs
node06-path
node07-http
node08-express
node09-cookie
http模块:
文件上传:
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>post</title>
<link rel="stylesheet" href="post.css">
</head>
<body>
<form action="/post" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="user"><br>
密码:<input type="password" name="pass"><br>
<input type="file" name="fileup"><br>
<input type="submit" value="提交">
</form>
<div id="time">time</div>
</body>
<script src="post.js"></script>
</html>
js:
window.onload = function(){
var time = document.getElementById("time");
var timer = setInterval(function(){
var ajax = new XMLHttpRequest();
ajax.open("get","/ajax?user=zhaoyang&pass=123",true);
ajax.send();
ajax.onload = function(){
time.innerHTML = ajax.responseText;
}
},1000); }
node(文件上传与get、post请求处理):
/*
* http:超文本传输协议
* http模块:能够搭建服务器环境(模拟的客服端环境)
*
* */ var http = require("http");
var url = require("url");
var fs = require("fs");
var formidable = require("formidable");
var server = http.createServer(function (request,response) {
// console.log(request.url);
var urlObj = url.parse(request.url,true);
// console.log(urlObj);
// console.log(request.method);
// response.end("响应结束"); if(urlObj.pathname == "/10post.html" || urlObj.pathname == "/"){
//访问表单页面
var rs = fs.createReadStream("10post.html");
rs.pipe(response);
// response.end();不能带end()
}else if(urlObj.pathname == "/post"){
// console.log(urlObj);
// request.on("data",function(chunk){
// console.log(chunk);
// }); var form = new formidable.IncomingForm();
form.parse(request,function (err,fields,files) {
// console.log(fields);
console.log(files);
console.log(files.fileup.path);//文件上传的临时路径 files.fileup.path
fs.createReadStream(files.fileup.path).pipe(fs.createWriteStream("./upload/" + files.fileup.name)); });
response.end();
}else if(urlObj.pathname == "/ajax"){
var newTime = new Date();
response.end(newTime.toString());
}else if(urlObj.pathname == "/req"){
console.log(urlObj.query);
var result= "";
request.on("data",function(chunk){
result += chunk.toString();
});
request.on("end",function(err){
response.end("参数是" + result);
})
response.end("参数是" + JSON.stringify(urlObj.query));
}else if(urlObj.pathname != "/favicon.ico"){
//其他的所有页面
// ./post.css
console.log(urlObj.pathname);
fs.createReadStream("." + urlObj.pathname).pipe(response);
}
});
server.listen(2333);
GET、POST请求:
var http = require("http");
var request = http.request({
host:"localhost",
port:"2333",
path:"/req?user=zhaoyang&pass=123",
// path:"/req",
method:"POST",
},function (res) {
console.log(res.statusCode);
var result = "";
res.on("data",function(chunk){
result += chunk;
});
res.on("end",function(err){
console.log(result);
});
});
request.write('{"user":"zhaoyang","pass":"123"}');
request.end();//结束请求体