})
req.write(contents);
//结束请求,否则服务器将不会收到信息
req.end();
//响应的数据为
{
"user1" : {
"name" : "mahesh",
"password" : "password1",
"profession" : "teacher",
"id": 1
},
"user2" : {
"name" : "suresh",
"password" : "password2",
"profession" : "librarian",
"id": 2
}
}
客户端发起http请求,请求方法为post,post传递数据,匹配路径是/users,服务器响应请求并返回数据user.json里的内容。
put
//http客户端
const http = require("http");
// 发送请求的配置
let config = {
host: "localhost",
port: 3000,
path:"/list",
method: "put",
headers: {
a: 1
}
};
// 创建客户端
let client = http.request(config, function(res) {
// 接收服务端返回的数据
let repData='';
res.on("data", function(data) {
repData=data.toString()
console.log(repData)
});
res.on("end", function() {
// console.log(Buffer.concat(arr).toString());
});
});
// 发送请求
client.end();
客户端发起http请求,请求方法为put,服务端收到put请求,匹配路径为/list,响应数据:put ok
delect
//http delete请求客户端
var http = require('http');
var querystring = require("querystring");
var contents = querystring.stringify({
name: "艾利斯提",
email: "m778941332@163.com",
address: " chengdu",
});
var options = {
host: "localhost",
port: 3000,
path:'/detail',
method: "DELETE",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": contents.length
}
};
var req = http.request(options, function (res) {
res.setEncoding("utf8");
res.on("data", function (data) {
console.log(data);
})
})req.write(contents);
req.end();
服务端收到delete请求,匹配路径为/detail,响应数据:delete ok









