0

I am creating rest web service using express nodejs framework. I want to navigate to second.js page from first.js and need to send data and header to it.

first.js

const express = require("express");
const http = require("http");

var router = express.Router();

var options = {
  host: "localhost",
  port: "3000",
  path: "/second",
  method: "POST"
};

router.get("/", function(req, res, next) {
  http.request(options);
});

module.exports = router;

second.js

var express = require("express");
var router = express.Router();

router.get("/", function(req, res, next) {
  res.send("Hello");
});

module.exports = router;

app.js

app.use("/first", first);
app.use("/second", second);

I tried like above but it doesn't navigate to second.js web service. Does anyone know what I am doing wrong ?

N Sharma
  • 33,489
  • 95
  • 256
  • 444

2 Answers2

2

Your code is not performing a redirection. You are actually making a call from within the first endpoint to a second endpoint and acting more like a proxy.

A redirection is performed by calling res.redirect as defined in the express documentation at http://expressjs.com/en/api.html (Search for res.redirect). A redirection returns a HTTP redirect response that the users browser will follow to a new URL. Unfortunately, redirections do not allow headers to be passed and it will be executed as a GET call(This is what redirections are designed for.). You can include whatever query params you want in the URL though and set cookies (refer to How to forward headers on HTTP redirect)

Deadron
  • 5,135
  • 1
  • 16
  • 27
  • Thanks Deadron. I am trying to use POST now. I am sending like `var options = { host: config.host, port: config.port, path: "/second", body: JSON.stringify({ foo: "foo" }), method: "POST" };` but not getting in second.js `console.log(req.body);` I am getting empty object {} – N Sharma Sep 28 '17 at 17:21
  • If you are having issues using the http lib I suggest you make a new question. As it is, the code you posted is not even reading the response from the call to http.request. – Deadron Sep 28 '17 at 17:36
1

I think you are using POST in your request

But only set up GET on your second endpoint

James Maa
  • 1,764
  • 10
  • 20
  • I tried with GET also but not working. it keeps spinning wheel and getting Abort / timeout when I try "http://localhost:3000/first" – N Sharma Sep 28 '17 at 16:36
  • @Nancy That's because you are not sending a message back in `first`, you should send you response after you finish the http request – James Maa Sep 28 '17 at 16:41
  • Thanks. I want to send the dynamic data into header. Do you know how to send ? – N Sharma Sep 28 '17 at 17:06
  • I am sending like `var options = { host: config.host, port: config.port, path: "/second", body: JSON.stringify({ foo: "foo" }), method: "POST" };` but not getting in second.js `console.log(req.body);` I am getting empty object {} – N Sharma Sep 28 '17 at 17:16