«

Node.js请求request

emer 发布于 2019-6-20 09:10   2252 次阅读     


Node.js发送请求

npm install request --save 

GET请求

 var url = 'http://192.168.0.102:3000/home?name=xmg' // 发送Get请求 // 第一个参数:请求的完整URL,包括参数 // 第二个参数:请求结果回调函数,会传入3个参数,第一个错误,第二个响应对象,第三个请求数据 request(url,function (error, response, data) { console.log(data)

}); 

Post请求

application/x-www-form-urlencoded

var url = 'http://192.168.0.102:3000/home?name=xmg' request.post({url:url, form:{key:'value'}}, function(error, response, body) { if (!error && response.statusCode == 200) {
    } 
    

})

application/json

var url = 'http://192.168.0.102:3000/home' request({ url: url, method: "POST", json: true, headers: { "content-type": "application/json",
    }, body: JSON.stringify(requestData)
}, function(error, response, body) { if (!error && response.statusCode == 200) {
    }
}); 

multipart/form-data

 var url = 'http://192.168.0.102:3000/home' var formData = { // Pass a simple key-value pair my_field: 'my_value', // Pass data via Buffers my_buffer: new Buffer([1, 2, 3]), // Pass data via Streams my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
};
request.post({url:url, formData: formData}, function (error, response, body) { if (!error && response.statusCode == 200) {
    }
})