Node.js7---post请求

本文通过一个实例展示了如何在Node.js环境中使用fetch和http模块实现POST请求,包括设置请求头、数据格式以及处理响应。重点强调了使用https.request而非https.post,并解释了headers中Content-Type与req.write数据格式的一致性要求。
摘要由CSDN通过智能技术生成

post请求

比如我们要仿小米优品,发送一个post请求,如下图:
请添加图片描述
我们可以这样写:

//index4.html
<!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>
    <script>
        fetch("http://localhost:3000/api/post").then(res => res.json()).then(res => {
            // 发post请求
            console.log(res)
        })
    </script>
</body>
</html>

//post.js
var http = require('http')
var https = require('https')
var url = require('url')

http.createServer((req, res) => {
    var urlobj = url.parse(req.url, true)
    res.writeHead(200, {
        "Content-Type": "application/json;charset=utf-8",
        //响应头 允许所有域通过控制,可以随便访问
        "access-control-allow-origin": "*"
    })
    console.log(urlobj.query.callback)
    switch (urlobj.pathname) {
        case "/api/post":
            //node作为客户端去小米优品要数据
            httppost((data) => {
                res.end(data)
            })
            break;
        default:
            res.end('404')
    }

}).listen(3000)


function httppost(cb) {
    var data = ""
    var options = {
        hostname: "m.xiaomiyoupin.com",
        port: '443',
        path: '/mtop/market/search/placeHolder',
        method: 'POST',
        headers: {
            //json
            "Content-Type": "application/json"
            //x-www-form-urlencoded
            // "Content-Type": "x-www-form-urlencoded"
        }
    }
    var req = https.request(options, (res) => {
        res.on("data", chunk => {
            data += chunk
        })
        res.on("end", () => {
            cb(data)
        })
    })
    //传json
    req.write(JSON.stringify([{}, { "baseParam": { "ypClient": 1 } }]))

    //x-www-form-urlencoded
    // req.write("name=xiaoming&age=27")
    req.end()
}

启动命令node .\post.js运行后效果如下:
请添加图片描述
请添加图片描述
需要注意的是,发送post请求需要用到https.request而不是https.post,因为https没有https.post方法。然后,headers里写的如果是json那req.write里就要写成json,否则,如果headers里写的是x-www-form-urlencoded那req.write里就要写成x-www-form-urlencoded。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值