Post请求
var http=require(‘http‘); var qs=require(‘querystring‘); var post_data={a:123,time:new Date().getTime()};//这是需要提交的数据 var content=qs.stringify(post_data); var options = { host: ‘127.0.0.1‘, port: 8080, path: ‘/admin‘, method: ‘POST‘, headers:{ ‘Content-Type‘:‘application/x-www-form-urlencoded‘,//post请求需要设置的type值 ‘Content-Length‘:content.length } }; console.log("post options:\n",options); console.log("content:",content); console.log("\n"); var a=‘‘ var req = http.request(options, function(res) { console.log("statusCode: ", res.statusCode); console.log("headers: ", res.headers); var _data=‘‘; res.on(‘data‘, function(chunk){ _data += chunk; a=chunk; }); res.on(‘end‘, function(){ console.log("\n--->>\nresult:",_data) }); }); req.write(content); req.end(); http.createServer(function (request, response) { // 发送 HTTP 头部 // HTTP 状态值: 200 : OK // 内容类型: text/plain response.writeHead(200, {‘Content-Type‘: ‘text/plain‘}); response.write(a) // 发送响应数据 "Hello World" response.end(‘Hello World\n‘); }).listen(8888);
在服务中解析Post请求参数
var express=require(‘express‘); var app=express(); var bodyParser = require("body-parser"); app.use(bodyParser.urlencoded({ extended: false })); app.post(‘/admin‘,(req,res)=>{ console.log(req) var data={ code:200, msg:‘success‘ } res.json(data); }) app.listen(8080,()=>{ console.log(8080) })