目录
一、初识req(request)和res(response)
一、初识req(request)和res(response)
1.1 服务器处理req和res
1.2 nodejs启动web服务
- 使用http模块,启动服务
- 本机IP:127.0.0.1
- 本机域名:localhost
- 在当前根目录下通过 node x.js来运行web服务
在浏览器里输入:localhost:3000来访问
注意:
这里我们可以通过npm安装 nodemon包,以此来简化运行等
输入,npm install nodemon –save-dev
安装成功后在package.json文件里做如下更改即可:
然后便可在终端里输入,npm run dev来运行服务
1.3 示例
const http = require('http'); //获取http模块
// 执行 创建服务
const server = http.createServer(() => {
console.log('已经收到http请求');
})
//监听端口
server.listen(3000);
console.log('http请求已经被监听,3000端口');
二、路由
2.1 初识路由
路由包含什么:
定义method,如POST、GET等
定义url规则,如api/list和api/create
定义输入(Request body)和输出(Response body)格式
路由是什么:
– router
– 服务端的入口规则
– 和前端的约定
路由是规则,url是具体的形式
2.2 GET请求
示例1:
//获取http模块
const http = require('http');
// 执行 创建服务
const server = http.createServer((req, res) => {
//获取url
const url = req.url;
//分割
const path = url.split('?')[0];
//
const method = req.method
console.log('url is:', url);
// console.log('method is:', method);
//定义路由:模拟获取留言板列表
if (path === '/api/list' && method === 'GET') {
res.end('this is list router');
}
res.end('404');
});
//监听端口
server.listen(3000);
console.log('http请求已经被监听,3000端口');
示例2:
index.js,
// 入口
var server = require("./server.js");
var handler = require("./handler");
var route = require("./router.js")
var handle = {};
handle["/"] = handler.home
handle["/home"] = handler.home
handle["/user"] = handler.user
handle["/list"] = handler.list
server.startServer(route,handle);
router.js,
var fs = require("fs");
function route(handle,pathname,response,params){
if(typeof handle[pathname] === 'function'){
handle[pathname](response,params)
}else{
response.writeHead(404,{"Content-Type":'text/html'});
fs.createReadStream(__dirname +"/404.html",'utf8').pipe(response)
}
}
module.exports = route;
handle.js,
var fs = require("fs");
var data = require("./data.js")
// / /home
function home(response){
response.writeHead(200,{"Content-Type":'text/html'});
fs.createReadStream(__dirname + "/home.html","utf8").pipe(response)
}
// /user
function user(response){
response.writeHead(200,{"Content-Type":'application/json'});
response.end(JSON.stringify(data))
}
// list
function list(response,params){
response.writeHead(200,{"Content-Type":'application/json'});
console.log(params);
response.end(JSON.stringify(params))
}
module.exports = {
home,
user,
list
}
server.js,
var http = require("http");
var url = require("url");
var querystring = require("querystring");
function startServer(route, handle) {
var server = http.createServer(function(request, response) {
// 拿到路径 例如:localhost:3000/list
var pathname = url.parse(request.url).pathname;
var params = url.parse(request.url, true).query;
route(handle, pathname, response, params);
})
server.listen(3000, "127.0.0.1");
console.log("服务器运行在3000端口上");
}
module.exports = {
startServer
}
2.3 POST请求
前提:安装Postman
示例1:
//获取http模块
const http = require('http');
// 执行 创建服务
const server = http.createServer((req, res) => {
//获取url
const url = req.url;
//分割
const path = url.split('?')[0];
//
const method = req.method
console.log('url is:', url);
// console.log('method is:', method);
//定义路由:模拟获取留言板列表
if (path === '/api/list' && method === 'GET') {
res.end('this is list router');
}
//定义路由,模拟创建留言
if (path === '/api/create' && method === 'POST') {
res.end('this is create router');
}
res.end('404');
});
//监听端口
server.listen(3000);
console.log('http请求已经被监听,3000端口');
示例2:
index.js,
// 入口
var server = require("./server.js");
var handler = require("./handler");
var route = require("./router.js")
var handle = {};
handle["/"] = handler.home
handle["/home"] = handler.home
handle["/user"] = handler.user
handle["/list"] = handler.list
server.startServer(route,handle);
router.js,
var fs = require("fs");
function route(handle, pathname, response, params) {
if (typeof handle[pathname] === 'function') {
handle[pathname](response, params)
} else {
response.writeHead(404, { "Content-Type": 'text/html' });
fs.createReadStream(__dirname + "/404.html", 'utf8').pipe(response)
}
}
module.exports = route;
handle.js,
var fs = require("fs");
var data = require("./data.js")
// / /home
function home(response){
response.writeHead(200,{"Content-Type":'text/html'});
fs.createReadStream(__dirname + "/home.html","utf8").pipe(response)
}
// /user
function user(response){
response.writeHead(200,{"Content-Type":'application/json'});
response.end(JSON.stringify(data))
}
// list
function list(response,params){
response.writeHead(200,{"Content-Type":'application/json'});
// var lists = [
// {
// name:"iwen"
// },
// {
// name:"ime"
// }
// ]
console.log(params);
response.end(JSON.stringify(params))
}
module.exports = {
home,
user,
list
}
server.js,
var http = require("http");
var url = require("url");
var querystring = require("querystring");
function startServer(route, handle) {
var server = http.createServer(function(request, response) {
//GET请求
// 拿到路径 例如:localhost:3000/list
var pathname = url.parse(request.url).pathname;
//存放POST请求的参数
var data = [];
//监听
request.on("error", function(err) {
console.log(err);
}).on("data", function(chunk) { //如果没有错误就监听data,读取POST请求的数据
data.push(chunk);
}).on("end", function() { //监听数据结果
// 如果是POST请求
if (request.method === "POST") {
//合并读取的数据,并转换为字符串
data = Buffer.concat(data).toString();
//querystring.parse(data) 将数据转换成对象类型
console.log(data);
route(handle, pathname, response, querystring.parse(data));
} else { //如果是GET请求
//得到get请求后面的参数
var params = url.parse(request.url, true).query;
route(handle, pathname, response, params);
}
})
})
server.listen(3000, "127.0.0.1");
console.log("服务器运行在3000端口上");
}
module.exports = {
startServer
}
home.html,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="/list" method="post">
name <input type="text" name='name'> password <input type="text" name='password'>
<input type="submit" value="Submit">
</form>
</body>
</html>
当点击提交过后:
:
今天的文章nodejs router_nodejs接收post请求分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/86672.html