一、读取静态资源
1、在node项目的src目录,建立www目录,放置music项目文件
2、在src目录,建立index.js
const http = require('http')
const path = require('path')
const fs = require('fs')
let server = http.createServer((req,res)=>{
if (req.url == "favicon.ico") return;
console.log(req.url);
if (req.url.startsWith('/music')){
fs.readFile(path.join(__dirname,'www',req.url),(err,data)=>{
if(err) throw err;
res.end(data);
})
} else {
}
})
server.listen('8085')
在cmd中,进入src目录,输入:node index.js
在浏览器中,输入:
二、实现登录
前端采用jquery的ajax请求。
后端采用node编写,采用两种方式(get、post)实现登录,get请求采用getlogin;post采用postlogin登录
1、编写服务端
由于要解析地址获取请求参数,导入:
const querystring=require('querystring')
const url=require('url')
完整代码:
const http = require('http')
const path = require('path')
const fs = require('fs')
const querystring=require('querystring')
const url=require('url')
let server = http.createServer((req,res)=>{
if (req.url == "favicon.ico") return;
console.log(req.url);
if (req.url.startsWith('/music')){
fs.readFile(path.join(__dirname,'www',req.url),(err,data)=>{
if(err) throw err;
res.end(data);
})
} else if(req.url.startsWith('/getlogin')){
if (url.parse(req.url,true).query.username){
let username = url.parse(req.url,true).query.username;
let password = url.parse(req.url,true).query.password;
res.end(username);
} else {
res.end('404');
}
} else if(req.url.startsWith('/postlogin')){
let allData = '';
req.on('data',chunk=>{
allData+=chunk;
})
req.on('end',()=>{
console.log("allData:"+allData);
allData = "/postlogin?"+allData;
if (url.parse(allData,true).query.username){
let username = url.parse(allData,true).query.username;
let password = url.parse(allData,true).query.password;
res.end(username);
} else {
res.end('404');
}
})
} else {
}
})
server.listen('8085')
2、客户端
2.1采用get请求
var username = $('#username').val();
var pwd = $('#pwd').val();
var rememberpwd = $('#rememberpwd').prop('checked');
//采用ajax验证
// 采用get方法
var sendData = "username="+username+"&password="+pwd;
var url="http://localhost:8085/getlogin?"+sendData;
$.ajax({
type:'get',
url:url,
success:function(data){
console.log(data);
if (data!="404"){
$('#usr').text("欢迎"+data+"登录");
$('.loginForm').hide();
} else {
alert('登录失败');
}
},
error:function(err){
console.log(err);
alert('登录失败');
}
});
2.2采用post请求
var username = $('#username').val();
var pwd = $('#pwd').val();
var rememberpwd = $('#rememberpwd').prop('checked');
//采用ajax验证
//采用post方法
var url="http://localhost:8085/postlogin";
$.ajax({
type:'post',
url:url,
data:{
username:username,
password:pwd
},
success:function(data){
console.log(data);
if (data!="404"){
$('#usr').text("欢迎"+data+"登录");
$('.loginForm').hide();
} else {
alert('登录失败');
}
},
error:function(err){
console.log(err);
alert('登录失败');
}
});
三、效果图
打开登录
登陆后