node.js - 如何在express服务器中进行API调用

标签 node.js express axios

我正在尝试在快速服务器中发出 get 请求,目前服务器只是打印所有 post 请求并且工作正常,问题是当发出 GET 请求时,响应返回为“未定义”

var env = process.env.NODE_ENV || "development";
var config = require("./config")[env];

const express = require("express");
const bodyParser = require("body-parser");
const axios = require("axios");
const app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

const hostname = config.server.host;
const port = config.server.port;

app.post("/", (req, res) => {
  console.log(req.body);
  res.sendStatus(200);

  axios
    .get("https://reqres.in/api/products/3")
    .then(response => {
      console.log(response);
    })
    .catch(error => {
      console.log(error.response);
    });
});

app.listen(port, hostname, () =>
  console.log(`Server running at http://${hostname}:${port}/`)
);

最佳答案

使用Postman将 Api 调用发送到服务器。我在下面附上链接。

  • 如果您使用的是 Chrome,请安装 Postman Chrome 扩展程序。
  • 使用 Localhost:port 服务器和 post 方法并添加变量来发布查询

希望这有帮助。

此外,只需在代码中添加此调整并在适当的本地主机上监听即可,

var env = process.env.NODE_ENV || "development";
var config = require("./config")[env];

const express = require("express");
const bodyParser = require("body-parser");
const axios = require("axios");
const app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

const hostname = config.server.host;
const port = config.server.port;

app.post("/", (req, res) => {
  console.log(req.body);
  res.sendStatus(200);

  axios
    .get("https://reqres.in/api/products/3")
    .then(response => {
      console.log(response);
    })
    .catch(error => {
      console.log(error.response);
    });
});

app.listen(1337, function(){
  console.log('Express listening on port', this.address().port);
});

关于node.js - 如何在express服务器中进行API调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58297544/

相关文章:

javascript - JS Express 连接到 mongoose 数据库

node.js - Passport js本地策略自定义回调 "Missing credentials"

javascript - 处理 Typescript 中的 Promise 捕获

json - 如何在 Cloud Functions for Firebase 中使 HTTP 请求异步/等待?

node.js - Node - ENONET 连接到套接字时

javascript - Sequelize belongsTo 关联给出错误 "table name "联系“指定不止一次”

javascript - express + cors() 无法正常工作

amazon-web-services - 使用 axios 和 aws4 向 aws 进行身份验证

javascript - 如何升级 Node 文件中的特定包?

node.js - 如何将缓冲区包装为 stream2 可读流?