<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>用户的参数传递</h1>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script type="text/javascript" src="./node_modules/axios/dist/axios.js"></script>
<h2>用户GET登录</h2>
<form id="myForm">
<input type="text" name="name" placeholder="用户名"><br>
<input type="password" name="password" placeholder="密码"><br>
<input type="submit" value="登录">
</form>
<hr>
<h1>用户POST登录</h1>
<form id="postForm">
<input type="text" name="name" placeholder="用户名"><br>
<input type="password" name="password" placeholder="密码"><br>
<input type="submit" value="登录">
</form>
</body>
<script type="text/javascript">
$("#myForm").submit(()=>{
console.log($("#myForm").serialize())
$.ajax({
url:"http://localhost:3000/userLoginApi",
data:$("#myForm").serialize(),
type:"GET",
success:(data)=>{
console.log(data)
},
dataType:"json",
error:(xhr,status,error)=>{
console.log(error)
}
})
return false;
})
//-------------------------------------------------------------------
$("#postForm").submit(()=>{
$.ajax({
url:"http://localhost:3000/userLoginApi",
type:"POST",
data:$("#postForm").serialize(),
success:(data)=>{
console.log(data)
},
dataType:"json",
error:(xhr,status,error)=>{
console.log(status,error)
}
})
return false;
})
</script>
</html>
var http=require("http")
var url=require("url")
var querystring=require("querystring")
var fs=require("fs")
http.createServer((req,res)=>{
var obj=url.parse(req.url)
if(obj.pathname!="/favicon.ico"){
if(req.method=="GET"){
if(obj.pathname=="/userLoginApi"){
var params=querystring.parse(obj.query)
var result={}
if(params){
if(params.name=="david"&¶ms.password=="123456"){
result.code=0;
result.data="success"
}else{
result.code=1;
result.data="fail"
}
}else {
result.code=2;
result.data="没有提交参数"
}
res.writeHead(200,{
"Content-Type":"text/plain;charset=utf8",
"Access-Control-Allow-Origin":"*"
})
res.end(JSON.stringify(result))
}else{
res.writeHead(404,{"Content-Type":"text/plain;charset=utf8"})
res.end("找不到对应的页面")
}
}else if(req.method=="POST"){
if(obj.pathname=="/userLoginApi"){
var tempData="";
req.on("data",(chuck)=>{
tempData+=chuck;
})
req.on("end",()=>{
console.log("tempData",tempData)
var params=querystring.parse(tempData)
var result={}
if(params){
if(params.name){
if(params.name=="david"&¶ms.password=="123456"){
result.code=0;
result.data="success"
}else{
result.code=1;
result.data="fail"
}
}else{
result.code=2;
result.data="没有提交参数" }
}
res.writeHead(200,{
"Content-Type":"text/html;charset=utf8",
"Access-Control-Allow-Origin":"*"
})
res.end(JSON.stringify(result))
})
}
}
}
}).listen(3000,()=>{
console.log("服务器运行在3000端口")
})