Node.js 如何使用http将API从一个节点服务器读取到另一个节点服务器?
我有两个节点应用程序在localhost:4000和localhost:5001上运行 我想将员工集合从localhost:4000读取到localhost:5001 如何实现 我试过这个, 但是没有成功Node.js 如何使用http将API从一个节点服务器读取到另一个节点服务器?,node.js,Node.js,我有两个节点应用程序在localhost:4000和localhost:5001上运行 我想将员工集合从localhost:4000读取到localhost:5001 如何实现 我试过这个, 但是没有成功 const https = require('https') const options = { hostname: 'localhost', port: 4000, path: '/employee', method: 'GET' } const req = https.request(
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()
我希望从employees集合中读取所有员工。但它显示了如下错误
错误:write EPROTO 9996:错误:1408F10B:SSL例程:ssl3_get_记录:错误的版本号:c:\ws\deps\openssl\openssl\SSL\record\ssl3_记录。c:332:
at WriteWrap.afterWrite [as oncomplete] (net.js:788:14) errno: 'EPROTO', code: 'EPROTO', syscall: 'write' .
我们是否有http来执行此操作。使用,它可以在客户端和服务器应用程序中使用
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);
});