在nodejs的開發(fā)中祠丝,有時需要后臺去調(diào)用其他服務(wù)器的接口栓撞,這個時候杠氢,就需要發(fā)送HTTP請求了
現(xiàn)在我們來模擬一下簡單地?cái)?shù)據(jù)請求
//request.php
<?php
echo 10;
?>
1.當(dāng)然也可以使用axios來發(fā)送請求
具體方式請看這個:http://www.reibang.com/p/e36956dc78b8
2.當(dāng)時我們使用request來發(fā)送這個請求
a). 現(xiàn)在我們通過express來搭建一個項(xiàng)目
(具體流程自行百度吧氯哮,教程很多掂碱。者甲。)
b). 安裝request模塊
cnpm install request --save-dev
c). 然后在routes下的index.js文件下寫我們的請求
var express = require('express');
var router = express.Router();
//引入request模塊
var request = require("request");
/* GET home page. */
router.get('/', function(req, res, next) {
//向我們剛才創(chuàng)建的request.php文件發(fā)起請求
request('http://localhost/node-request/php/request.php', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // 打印獲取到的數(shù)據(jù)撞蚕,這里輸出10
}
})
//渲染主頁
res.render('index', { title: 'Express'});
});
module.exports = router;
d). POST application/json
//requestJson.php
<?php
$obj = '{"age":20}';
echo json_encode($obj);
?>
e). GET請求
這時候index.js文件下是這樣的
var express = require('express');
var router = express.Router();
var request = require("request");
/* GET home page. */
router.get('/', function(req, res, next) {
request({
url: "http://localhost/node-request/php/requestJson.php",
method: "GET",
json: true,
headers: {
"content-type": "application/json",
}
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
body = JSON.parse(body);
console.log(body.age);//這里輸出的是20
}
});
res.render('index', { title: 'Express'});
});
module.exports = router;
對于請求中傳遞參數(shù),如果是get方法的話过牙,直接將參數(shù)拼接到url后面就好了
f). 對于post請求
request.post('http://service.com/upload', {form:{key:'value'}})
// or
request.post('http://service.com/upload').form({key:'value'})
// or
request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ })
對于多部分/表單數(shù)據(jù)甥厦,我們使用@ FelixGE格式數(shù)據(jù)庫。對于大多數(shù)情況下寇钉,您可以通過FromDATA選項(xiàng)傳遞您的上傳表單數(shù)據(jù)刀疙。
var formData = {
// Pass a simple key-value pair
my_field: 'my_value',
// Pass data via Buffers
my_buffer: Buffer.from([1, 2, 3]),
// Pass data via Streams
my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
// Pass multiple values /w an Array
attachments: [
fs.createReadStream(__dirname + '/attachment1.jpg'),
fs.createReadStream(__dirname + '/attachment2.jpg')
],
// Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}
// Use case: for some types of streams, you'll need to provide "file"-related information manually.
// See the `form-data` README for more information about options: https://github.com/form-data/form-data
custom_file: {
value: fs.createReadStream('/dev/urandom'),
options: {
filename: 'topsecret.jpg',
contentType: 'image/jpeg'
}
}
};
request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});