首先,学了好久 node ,终于受不了 命令行来执行 node,转到了 chrome 来输出 node 信息,天朗气清。
教程一搜一大把,就不介绍了
1 http.createServer(function (req, res) { 2 res.writeHead(200, {'Content-type': 'text/plain; charser=utf-8', 3 'Access-Control-Allow-Credentials': true, 4 'Access-Control-Allow-Origin': '*'}) // 跨域
用了 chrome 调试之后,自然就会手贱的 什么东西都输出一下
console.log(req);
在 res 里有各种 各样的参数可供选择,
比较常用的就有 : headers 、url、 method
没错 ,这里直接就有 method 可以判断请求方法。
console.log(req.method === 'POST'); // true
//==========================================
1 const http = require('http'); 2 const querystring = require('querystring'); 3 const url = require('url'); 4 const util = require('util'); 5 6 http.createServer(function (req, res) { 7 res.writeHead(200, // 支持跨域 8 {'Content-type': 'text/plain; charser=utf-8', 9 'Access-Control-Allow-Credentials': true, 10 'Access-Control-Allow-Origin': '*'}) 11 12 let mypath = url.parse(req.url).pathname; // 拿到 请求的 路径 如 /login 13 if (req.method === 'POST') { // 根据 请求的 方法,选择 函数 14 toPost(req, res, mypath); 15 } else if (req.method === 'GET') { 16 toGet(req, res, mypath); 17 } 18 }).listen(3000); 19 20 function toPost (req, res, mypath) { 21 let post = ''; 22 req.on('data', function (chunk) { // 接受请求体中的 数据 23 post += chunk; 24 }); 25 req.on('end', function () { 26 post = querystring.parse(post); 27 console.log(mypath); 28 console.log(post); 29 if (mypath === '/login') { // 根据 请求的 路径执行 对应的 函数 30 login(res, post) 31 } 32 }); 33 } 34 function toGet (req, res, mypath) { 35 let params = url.parse(req.url, true).query; // get 方法获取 路径上的 参数 36 console.log(mypath); 37 res.write(`用户名:${params.name}`); 38 res.write('\n'); 39 res.write(`用户地址:${params.url}`); 40 res.end('欢迎访问'); 41 } 42 43 44 45 function login (res, {username, password}) { 46 console.log('Logining') 47 console.log(username); 48 console.log(password); 49 if (username == 2 && password == 3) { 50 console.log('Logining') 51 res.end(`欢迎 用户 ${username}`); // 登陆成功之后的返回 52 } 53 }
html:
这样就能 使用 post 方法 访问
http://localhost:3000/login
传递数据: data:{username: 2,password: 3}
1 xmlhttp.open('post', 'http://localhost:3000/login', true); 2 // 以 form 表单的形式 发送数据 name=value 3 xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); 4 // so 这里发送的数据也 要按照这个格式 5 xmlhttp.send('username=2&password=3')