服务器到服务器/路由到 Express 中的路由 Axios 请求

时间:2021-02-03 11:37:23

标签: node.js express axios

在一个路由中,我想用 Axios 发布一个内部 URL - 这可能吗? (或者这仅仅是本地主机问题?)

内部路线:

exports.route = async (req, res) => {
  try {
    const data = await db.query(
      `select * from something where id ='${req.params.id}';`
    );

    const returnedData = await axios.post(`/all-data`);

    console.log(returnedData);

.....

其中所有数据是现有路线。 (app.post....)

但是运行此代码会出现错误:

Error: connect ECONNREFUSED 127.0.0.1:80
        at TCPConnectWrap.afterConnect [as oncomplete] (net.js:116:16) {
      errno: -111,
      code: 'ECONNREFUSED',
      syscall: 'connect',
      address: '127.0.0.1',
      port: 80,

.....

我可以为内部路由进行这样的服务器到服务器调用吗?

1 个答案:

答案 0 :(得分:1)

您应该为 axios 设置整个 URL。

例如

import express from 'express';
import axios from 'axios';

const app = express();
const port = 3000;

app.get('/', async (req, res) => {
  const returnedData = await axios.post(`http://localhost:${port}/all-data`).then((response) => response.data);

  res.send(returnedData);
});

app.post('/all-data', (req, res) => {
  res.json({ name: 'teresa teng' });
});

app.listen(port, () => console.log(`HTTP server started at http://localhost:${port}`));

通过 curl 测试:

⚡  curl -i -X GET http://localhost:3000
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 22
ETag: W/"16-ZsgB44rkFuiax9JQYtHnPMbo0dI"
Date: Thu, 04 Feb 2021 03:22:20 GMT
Connection: keep-alive
Keep-Alive: timeout=5

{"name":"teresa teng"}%