node js 发送http请求

来源:互联网 发布:java反射机制教程 编辑:程序博客网 时间:2024/06/05 07:02


get 请求


var url="http://apicloud.mob.com/lottery/list?key=1ebe77faca8b0";var http=require("http");http.get(url,function (req) {  var html="";  req.on("data",function (data) {      html+=data;  });  req.on("end",function () {      console.log(html);  });  req.on("error",function (error) {      console.log(error);  });})
// post 请求var http=require("http");var queryString=require("querystring");var data={    "menu":"红烧肉",    "key":"cad35b62a5b43c5bc9a98e01ba69532b"};var postData=queryString.stringify(data);console.log(JSON.stringify(data));var option={    host:"apis.juhe.cn", //不能加 http,默认已经http:    path:"/cook/query.php",    method:"POST",    headers:{        'Content-Type': 'application/x-www-form-urlencoded'        // 'Content-Length':Buffer.byteLength(postData)    }};var req=http.request(option,function (res) {    console.log('Status:',res.statusCode);    // console.log('headers:',JSON.stringify(res.headers));    var html="";    res.on("data",function (data) {        html=html+data;    });    res.on("end",function () {        console.log(html);    })});req.on("error",function (error) {    console.error(error);})req.write(postData);req.end();
//get
var http=require("http");var queryString=require("querystring");var data={    "menu":"红烧肉",    "key":"cad35b62a5b43c5bc9a98e01ba69532b"};var content=queryString.stringify(data);var options={    host:"apis.juhe.cn", //不能加 http,默认已经http:    path:"/cook/query.php?"+content,    method:"GET",};var req=http.request(options,function (res) {    var html="";   res.on("data",function (data) {       html=html+data;   });   res.on("end",function () {       console.log(html);   })});req.on("error",function (error) {    log.error(error);});req.end();


原创粉丝点击