var http=require(‘http‘); var request=require(‘request‘); var body = { "data":{ "id" : 11, "zjCount" : ‘zjCount‘, "number" : ‘number‘} } var bodyString = JSON.stringify(body); var headers = { ‘Content-Type‘: ‘application/json‘,//x-www-form-urlencoded post请求用这个 ‘Content-Length‘: bodyString.length }; var options = { host: ‘127.0.0.1‘, port: 8080, path: ‘/admin?name=ooo&age=10‘, method: ‘get‘, headers: headers }; var responseString = ‘‘; // var req=http.request(options,function(res){ // res.setEncoding(‘utf-8‘); // res.on(‘data‘, function(data) { // responseString += data; // console.log(‘data‘,data); // }); // res.on(‘end‘, function(res) { // //这里接收的参数是字符串形式,需要格式化成json格式使用 // var resultObject = JSON.parse(responseString); // console.log(‘end‘,res); // }); // req.on(‘error‘, function(e) { // // TODO: handle error. // console.log(‘-----error-------‘,e); // }); // }); // req.write() // req.end(); // const server = http.createServer((req, res) => { // console.log(req.url) // res.writeHead(200,{‘Content-Type‘:‘text/plain‘}) // if(req.url===‘/admin‘){ // res.write(responseString); // res.end(‘ssss‘); // }else{ // res.write(‘jjjj‘) // res.end(‘ssss‘); // } // }); var server = new http.Server(); server.on(‘request‘,(req,res)=>{ console.log(req.url); //设置应答头信息 res.writeHead(200,{‘Content-Type‘:‘text/html‘}); res.write(responseString); res.end(‘server already end\n‘); }); function a() { console.log(‘this is function a‘) } server.on(‘clientError‘, (err, socket) => { socket.end(‘HTTP/1.1 400 Bad Request\r\n\r\n‘); }); server.on(‘connection‘,()=>{ a(); }); server.on(‘close‘,()=>{ console.log(‘server will close‘); }); server.close(); server.listen(8000);