• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

joer717

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

Node.js GET/POST请求

获取GET请求内容

var http = require('http');

var url = require('url');

var util = require('util');

http.createServer(

          function(req, res){

                              res.writeHead(200, {

                                       'Content-Type': 'text/plain;charset=utf-8'

                            });

                             res.end(util.inspect(url.parse(req.url, true)));

}).listen(3000);//监听的端口号

参数都在 url.parse(req.url, true).query;里面

 

 

获取post请求内容

post请求的内容都在请求体中

http.createServer(function (req, res) {
    // body,用于暂存请求体的信息
    var body = "";
    // 通过req的data事件监听函数,每当接受到请求体的数据,存到body
    req.on('data', function (chunk) {
        body += chunk;
    });
    // 在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回
    req.on('end', function () {
        // 解析参数
        body = querystring.parse(body);
        // 设置响应头部信息及编码
        res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});

        if(body.name && body.url) { // 输出提交的数据
            res.write("网站名:" + body.name);
            res.write("<br>");
            res.write("网站 URL:" + body.url);
        } else {  // 输出表单
            res.write(postHTML);
        }
        res.end();
    });
}).listen(3008);

 





 

posted on 2019-03-13 11:17  joer717  阅读(135)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3