1.8 GET/POST请求 🎉
...小于 1 分钟
1.8 GET/POST请求 🎉
获取Get请求内容 💎
// 浏览器访问地址 : http://localhost:3030/?name=lcl&age=10
// 引入http模块
const http = require('http')
const url = require('url')
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
const query = url.parse(req.url, true).query
for ([key, value] of Object.entries(query)) {
res.write(key + ':' + value)
}
res.end();
})
// 启动服务器并监听某个端口
server.listen('3030', () => {
console.log('服务器已做好准备,正在监听3030端口')
})
获取Post请求内容 💎
<form id="form1" action="http://localhost:3030" method="post">
姓名:<input type="text" name="name"><br />
年龄:<input type="text" name="age"><br />
<input type="submit" value="提交" onClick="(e)=>{e.preventDefault()}"/>
</form>
const http = require('http')
const querystring = require('querystring')
const server = http.createServer((req, res) => {
var bodyStr = ''
req.on('data', function (chunk) {
bodyStr += chunk
})
req.on('end', function () {
const body = querystring.parse(bodyStr);
// 设置响应头部信息及编码
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
if (body.name && body.age) {
res.write("姓名:" + body.name);
res.write("<br>");
res.write("年龄:" + body.age);
}
res.end()
});
})
// 启动服务器并监听某个端口
server.listen('3030', () => {
console.log('服务器已做好准备,正在监听3030端口')
})
Powered by Waline v2.15.7