Javascript Fastify:如何从.get/.post调用远程url

Javascript Fastify:如何从.get/.post调用远程url,javascript,fastify,Javascript,Fastify,目前正在进行fastify的工作,遇到了一个尚未解决的问题 这是当前使用的代码users.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

目前正在进行fastify的工作,遇到了一个尚未解决的问题

这是当前使用的代码users.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;
解决方案: 安装axios或

在代码开始处添加此行

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;