简体   繁体   中英

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.

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));
}

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