简体   繁体   中英

Chaining http requests using promises

In my function "reqHandler" I collect form data and pass it into my http.request. To chain requests, I declared a Promise and .then handler. Problem is that: 1. This is written into console "Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'url' of undefined" 2. It seems like .then is not invoked, so no API calls are made.

Code:

"use strict";

const http        = require("http");
const qs          = require("querystring");
const fs          = require("fs");
const PORT        = 3000;

let resObject = {};
let hash = "";

const options = {
  hostname: "netology.tomilomark.ru",
  path: "/api/v1/hash",
  method: "post"
};

const reqHandler = (req, res) => {
  return new Promise((resolve, reject) => {
    if (req.url === "/") {
      switch (req.method.toLowerCase()) {
        case "get":
          // Browse my form with "Name" and "Surname" inputs
          fs.readFile("./logs/form.html", (err, file) => {
            if (err) {
              reject("Promise rejected");
              return
            }
            res.writeHead(200, {'Content-Type': 'text/html','Content-Length':file.length});
            res.write(file);
            res.end();
          });
          break;
        case "post":
          // Collect form data and parse it using querystring
          let body = "";
          req.setEncoding("utf8");
          req.on("data", (data) => {
            body += data;
            if (body.length > 1e6)
              req.connection.destroy();
          });
          req.on("end", () => {
            let post = qs.parse(body);
            console.log(post);
            options.headers = {
              "Content-Type": "application/json",
              "firstname": `${post.firstName}`
            };
            options.body = {
              "lastname": `${post.lastName}`
            };
            // Resolve with "options" object that has headers and body
            resolve(options);
          });
          break;
        default:
          badRequest(res);
      }
    } else {
      notFound(res);
    }
  });
};

reqHandler()
  .then((options) => {
    http.request(options, (res) => {
      let resString = "";
      res.on("data", (data) => {
        resString += data;
      });
      res.on("end", () => {
        console.log(resString);
      });
      res.end();
    });
  })
  .catch(err => {throw err});

let badRequest = (res) => {
  res.statusCode = 400;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Bad Request');
};

let notFound = (res) => {
  res.statusCode = 404;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Not Found');
};

const server = http.createServer();
server.on("error", (err) => console.error(err));
server.on("request", reqHandler);
server.on("listening", () => console.log(`Start HTTP on port ${PORT}`));
server.listen(PORT);

Ultimately , what´s wrong with my promise and .then? Any help will be appreciated!

Ok I have create a test environment and here you have an abstract version of your source. Your mistakes was to wrap your promise in a function which pass the req and res parameters and you have to call resolve or reject inside your promise, what have been forgotten on several places.

This source is tested!

const http = require('http');

const reqHandler = (req, res) => {
  return new Promise((resolve, reject) => {
    if (req.url === "/") {
      switch (req.method.toLowerCase()) {
        case "get":
          console.log('get');
          return resolve('get');
        case "post":
          console.log('post');
          return resolve('post');
        default:
          return resolve('default');
      }
    } else {
      return resolve('some thing else');
    }
  });
};

const myReqHandler = (req, res) => {
    reqHandler(req, res).then(()=> {
        console.log('then reached')
    });
}


const PORT = 8089;
const server = http.createServer();
server.on("error", (err) => console.error(err));
server.on("request", myReqHandler);
server.on("listening", () => console.log(`Start HTTP on port ${PORT}`));
server.listen(PORT);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM