Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a NodeJS request and pipe it into another response

So, i'm doing an api, to query a certain map service which require an API key. I want to keep the API key private so in my own api on the server, I will call a http.request to the map service, then immediately pipe it into the response to my own api user.

Here is sample code to illustrate the idea:

import http from "http";

export default function handler(req, res) {
    http.request(`http://map.service.example.com/foo-bar`, (mapRes) => mapRes.pipe(res));
}

But so far, the code above doesn't work.

Any other possible way (with fetch maybe?) is welcome.

like image 822
vixalien Avatar asked Oct 31 '25 17:10

vixalien


1 Answers

For an http.request to go through you have to call its end method:

import http from "http";

export default function handler(req, res) {
    const mapReq = http.request(`http://map.service.example.com/foo-bar`, (mapRes) => mapRes.pipe(res));
    mapReq.end();
}

OR

You can use the get method:

import http from "http";

export default function handler(req, res) {
    http.get(`http://map.service.example.com/foo-bar`, (mapRes) => mapRes.pipe(res));
}
like image 122
gfpacheco Avatar answered Nov 02 '25 07:11

gfpacheco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!