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/

相关文章:

node.js - Firebird 查询 - 仅数字

node.js - Node+Passport.js + Sessions + 多台服务器

node.js - 快车4路未打通

javascript - 在哪里发送 JWT token ?

ajax - 使用 Axios 将某些 XHR 请求优先于其他请求

javascript - 按照 jest docs 模拟 axios 但不工作

php - 如何在 NODE.JS 上模仿 php crypt()

javascript - 在 Node.js 中的两个数组中查找匹配字符串的最有效和优雅的方法

node.js - 如何在 Wildfly 服务器上部署我的 NodeJS 应用程序

vue.js - axios多个异步上传的所有进度条