【问题标题】:How to read API from one node server to another Node server using http?如何使用 http 从一个节点服务器读取 API 到另一个节点服务器?
【发布时间】:2019-11-01 14:51:11
【问题描述】:

我有两个节点应用程序在 localhost:4000 和 localhost:5001 上运行。

我想从 localhost:4000 到 localhost:5001 读取 Employee 集合。

如何实现?

我试过这个, https://flaviocopes.com/node-make-http-requests/

但没有成功。

const https = require('https')
const options = {
hostname: 'localhost',
port: 4000,
path: '/employee',
method: 'GET'
}

const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)

res.on('data', (d) => {
 process.stdout.write(d)
})
})

req.on('error', (error) => {
console.error(error)
})

req.end()

我希望从员工集合中读取所有员工。但它显示错误如下

错误:写入 EPROTO 9996:error:1408F10B:SSL 例程:ssl3_get_record:错误的版本号:c:\ws\deps\openssl\openssl\ssl\record\ssl3_record.c:332:

at WriteWrap.afterWrite [as oncomplete] (net.js:788:14) errno: 'EPROTO', code: 'EPROTO', syscall: 'write' .

我们是否有 http 来执行此操作。

【问题讨论】:

    标签: node.js


    【解决方案1】:

    使用axios,它可以在客户端和服务器应用程序中使用。

    const axios = require('axios');
    
    callApi = (req, res) => {
        axios.get("http://localhost:5001",
                  { headers: { key:value }, params: { key:value } }
        ).then((response) => {
            res.status(200).send(response.data);
        }).catch((error) => {
            console.log(error);
            res.status(400).send(error.message);
        });
    };
    

    你也可以使用post,只需将axios.get更改为axios.post并在url后面添加另一个body对象

    axios.post('/user', {
        firstName: 'Fred',
        lastName: 'Flintstone'
      },
       { headers: { key:value }, params: { key:value } })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    

    【讨论】:

      猜你喜欢
      • 2017-11-13
      • 2018-09-25
      • 1970-01-01
      • 2019-01-16
      • 2017-04-07
      • 2019-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多