#nodejs post或get 请求获取参数

nodejs post或get 请求获取参数

1.get/post(未使用框架)

1). index.html(get/post)





Title


nodejs(get方式获取)

var http = require("http")
//注入一个解析模块
var url = require("url")
http.createServer(function (req,res) {
        //?name=asdas&sex=asdasd
        console.log(req.url);

        /*Url {
          protocol: null,
          slashes: null,
          auth: null,
          host: null,
          port: null,
          hostname: null,
          hash: null,
          search: '?name=asdas&sex=asdasd',
          query: { name: 'asdas', sex: 'asdasd' },
          pathname: '/',
          path: '/?name=asdas&sex=asdasd',
          href: '/?name=asdas&sex=asdasd' }*/
        //req.url解析为url对象 true深成次递归
        console.log(url.parse(req.url,true))
        res.end();
}).listen(7777)

nodejs(post方式获取)

var http = require("http")
//注入解析对象模块
var string = require("querystring")
http.createServer(function (req,res) {
        if(req.url == "favicon.ico"){
            res.end();
            return;
        }
        var  str = ""
        req.addListener("data",function (trunk) {
            str += trunk;
        })

        req.addListener("end", function () {
            //name=123123&sex=12312
            console.log(str.toString())
            //{ name: '123123', sex: '12312' }
            console.log(string.parse(str.toString()))
        })

}).listen(7777)

1.get/post(使用框架express)

1). index.html(get/post 使用ejs模板)

    
    
        
            
        
        
            

nodejs(get方式获取)

与未使用框架大同小异

nodejs(post方式获取)

1.post方式

var express = require("express")
var url = require("url");
var app = express();

//注入解析模块
var bodyParser = require('body-parser');
app.set("view engine","ejs")
//注入解析函数 每个请求都会触发这个解析函数
app.use(bodyParser.urlencoded({extended:false}));
app.get("/",function (req,res) {
    res.render("index",function (err,data) {
        res.send(data.toString())
    })
})

app.post("/aaaaa",function (req,res) {
    //post传入参数
    console.log(req.body)

})

app.listen(8888)

2.post方式(与未使用框架一样)

var express = require("express")
var url = require("url");
var app = express();
//注入解析模块
var string = require("querystring")

app.set("view engine","ejs")
app.get("/",function (req,res) {
    res.render("index",function (err,data) {
        res.send(data.toString())
    })
})
app.post("/aaaaa",function (req,res) {
    var str = ""
    req.addListener("data",function (trunk) {
        str += trunk;
    })

    req.addListener("end",function () {
        console.log(str.toString())
        //解析字符串
        console.log(string.parse(str.toString()))
    })


})

app.listen(8888)

你可能感兴趣的:(nodejs笔记)