nodejs的post请求

本文详细介绍了如何在Node.js环境中进行POST请求,包括使用内置http模块、axios库和request库的方法,涵盖设置请求头、发送JSON数据及处理响应等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form action="http://localhost:3000" method="post">
        <p>
            <input type="text" placeholder="请输入用户名" name="user">
        </p>
        <p>
            <input type="password" placeholder="请输入密码" name="pwd">
        </p>
        <p>
            <input type="submit" value="登录">
        </p>
    </form>
</body>

</html>
//引入服务器http
const http = require("http");
//引入url请求地址
const url = require("url");
const querystring = require("querystring")

//  post请求的数据 是添加到 请求体中  
http.createServer((req, res) => {

    //设置一个存储数据的容器
    let body = "";
    //监听data事件。有数据时触发
    req.on("data", (chunk) => {
        body += chunk;
    })

    //监听end事件 么有更多数据可读时触发
    req.on("end", () => {
        //传出的数据是字符串,要把它解析成对象
        body = querystring.parse(body);
        //设置请求头 200表示成功,后面的表示请求类型以及编码格式
        res.writeHead(200, { "Content-Type": "text/plain;charset=utf-8" })
        res.write(`欢迎 ${body.user}`)
        res.end()


    })
    let query = url.parse(req.url, true).query
        // console.log(query);

}).listen(3000, () => {
    console.log("hello word");
})

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值