node 判断请求的方法类型

1 篇文章 0 订阅

首先,学了好久 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')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值