美文网首页
get/post请求

get/post请求

作者: 张鸽 | 来源:发表于2017-07-31 20:16 被阅读0次

get和post方法都是http发送请求的方式,而不是字面上一个取,一个发。

  • get方法
    在 get方式中:
    参数都是以键值方式拼接在请求的 URL 当中的, 所以我们可以通过解析 URL 来获得参数.首先写一个表单来获取信息
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="http://127.0.0.1:3000/" method="get">
    <input type="text" name="name">
    <input type="text" name="url">
    <button type="submit">submit</button>
</form>
</body>
</html>

action 属性规定当提交表单时,向何处发送表单数据
解析URL的js文件,代码如下

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=utf8'});
    var a = url.parse(req.url, true).query;
    res.write('名字:' + a.name);
    res.write('\n');
    res.write('年龄:' + a.url);
    res.end();
}).listen(3000);

终端运行js文件的同时运行html文件,效果图如下

Paste_Image.png

输入内容


Paste_Image.png

点击提交


Paste_Image.png

完成解析

  • post方法
    post方式, 它会将参数数据添加到请求体中发送到服务端, 所以, 我们需要去解析 请求体中的数据来获取 post请求发送过来的参数.这里我们就需要使用 ‘querystring’ 这个库了, 用来处理 response 对象的数据
    首先表单获取信息,将get方法的html文件中
<form action="http://127.0.0.1:3000/" method="get">

改为

<form action="http://127.0.0.1:3000/" method="post">

解析请求体的代码如下

var http = require('http');
var querystring = require('querystring');
http.createServer(function (req, res) {
    var body = "";
    req.on('data', function (chunk) {
        body += chunk;
    });
    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);
        } 
        res.end();
    });
}).listen(3000);
Paste_Image.png Paste_Image.png

相关文章

  • iOS请求方法和网络安全

    GET和POST请求 GET和POST请求简介 GET请求模拟登陆 POST请求模拟登陆 GET和POST的对比 ...

  • iOS请求方法和网络安全

    GET和POST请求GET和POST请求简介GET请求模拟登陆POST请求模拟登陆GET和POST的对比保存用户信...

  • java发送http请求

    restTemplate get请求 post请求 apache.http.client get请求 post请求...

  • Get和Post的区别

    Get请求和Post请求区别如下: Post请求比Get请求更安全,get请求直接将参数放置在URL中,post请...

  • Okhttp3

    简介 配置 请求思路 get请求思路 post请求思路 get,post 同步和异步请求 异步请求(get) 同步...

  • gf框架 ghttp使用

    案例中包含以下内容 get请求 get请求携带参数 post请求携带参数 post请求发送xml数据 post请求...

  • HttpUtil工具

    HttpUtil工具,http get post请求,https get post请求,ajax response...

  • ajax 请求的时候 get 和 post 方式的区别?

    get和post的区别 get请求不安全,post安全 get请求数据有限制,post无限制 get请求参数会在u...

  • get和post请求区别

    get请求和post请求 差别 get请求回退时无反应,post请求回退时会再次发起请求。 GET请求只能进行ur...

  • iOS 的网络请求案例

    post请求: get请求:

网友评论

      本文标题:get/post请求

      本文链接:https://www.haomeiwen.com/subject/winrlxtx.html