node.js请求php接口

在nodejs的开发中,有时需要后台去调用其他服务器的接口,这个时候,就需要发送HTTP请求了

现在我们来模拟一下简单地数据请求
//request.php
<?php 
    echo 10;
 ?>
1.当然也可以使用axios来发送请求

具体方式请看这个:https://www.jianshu.com/p/e36956dc78b8

2.当时我们使用request来发送这个请求
a). 现在我们通过express来搭建一个项目

(具体流程自行百度吧,教程很多。。)

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) {
    //向我们刚才创建的request.php文件发起请求
    request('http://localhost/node-request/php/request.php', function (error, response, body) {
    
      if (!error && response.statusCode == 200) {
        console.log(body) // 打印获取到的数据,这里输出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;
对于请求中传递参数,如果是get方法的话,直接将参数拼接到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){ /* ... */ })
对于多部分/表单数据,我们使用@ FelixGE格式数据库。对于大多数情况下,您可以通过FromDATA选项传递您的上传表单数据。
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);
});
    原文作者:星球小霸王
    原文地址: https://www.jianshu.com/p/e1b7c5d869d4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞