0

目前在做 fastify 的时候遇到了一个没有解决办法的问题。

这是当前使用的代码。用户.js

async function routes(fastify, options) {
  // GET /users/:id
  fastify.get("/:id", async (req, res) => {
    // Create a remote request to any url for testing
    // https://jsonplaceholder.typicode.com/todos/1
  });
}

module.exports = routes;

我想向以下 URL 发出请求并返回其响应。这就是我正在尝试的方式。

async function routes(fastify, options) {
  // GET /users/:id
  fastify.get("/:id", async (req, res) => {
    // Create a remote request to any url for testing
    // https://jsonplaceholder.typicode.com/todos/1
    const response = await got;
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then(response => response.json())
      .then(json => {
        console.log(json);
        res.send({
          id: req.params.id,
          title: json.title,
          completed: json.completed,
          userId: json.userId
        });
      }).catch = err => {
      console.log(err);
    };
  });
}

module.exports = routes;
4

1 回答 1

0

解决方法:安装 axios 或者node-fetch

在代码开始时添加这一行。

const fetch = require("node-fetch");

获取示例代码以与 fastify .get 集成

async function routes(fastify, options) {
  /* GET /users/:id and fetch from remote server */
  fastify.get("/:id", async (request, response) => {
    // Create a remote request to any url for testing
    const remoteURL = "https://jsonplaceholder.typicode.com/todos/1";
    fetch(remoteURL)
      .then(response => response.json())
      .then(data => {
        console.log(data);
        const payload = {
          id: request.params.id,
          title: data.title,
          completed: data.completed
        };
        response.send(payload);
      })
      .catch(err => {
        console.log(err);
      });
  });
}

module.exports = routes;
于 2020-02-08T03:38:42.470 回答