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。