让前端飞

五:node——get方法

2018-06-18  本文已影响8人  椰果粒

get方法用来接受前台请求的数据

首先创建一个表单:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="http://localhost:7777/" method="get">
    用户名:<input type="text" name="user">
    密码:<input type="password" name="pass">
    <textarea name="text" id="" cols="30" rows="10"></textarea>
    <input type="submit" value="提交">
</form>
</body>
</html>

定义node服务器:

/*
* 如何接受前台的数据请求
* 方式:Form,Ajax,jsonp
* 请求方式:
*   get:数据在URL里
*   post:数据不在URL里
* */

const http = require("http")
const urlLib = require("url")

var getMethod = function(req,res){
    // get方式向服务器传递数据
    console.log(req.url)
    var obj = urlLib.parse(req.url,true)
    var url = obj.pathname
    var get = obj.query
    console.log(url,get)
}
http.createServer(getMethod).listen(7777)

运行结果:

// 请求的地址
/?user=zhangsan&pass=123&text=123
// 将参数转换成json数据
/ { user: 'zhangsan', pass: '123', text: '123' }

url模块:

举个例子

const urlLib = require("url")
var obj = urlLib.parse("http://www.baidi.com/index?a=10&=20",true)
console.log(obj.pathname)   // /index
console.log(obj.query)      // { a: '10', '': '20' }
上一篇 下一篇

猜你喜欢

热点阅读