0

So I need to create a endpoint i.e. A GET request in NodeJS which will make a curl call to another api and return a data. I am using native method of NodeJS to make curl call using https module. But I am not getting any response when I hit my nodeJS api (i.e. /api/mailers/campaigns). If I try to print curl response in console it returns me correct data. Is there anything I am missing?

Basically for security purpose I will hit my nodejs endpoint from my frontend

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

app.get('/api/mailers/campaigns', (req, res) => {
    var chunks = [];
    var options = {
        "method": "GET",
        "hostname": "api.mailerlite.com",
        "port": null,
        "path": "/api/v2/campaigns",
        "headers": {
            "x-mailerlite-apikey": "api_key",
            "content-type":"application/json"
        }
    };

    var req = http.request(options, function (res) {
        

        res.on("data", function (chunk) {
            chunks.push(chunk);
        });

        res.on("end", function () {
            var body = Buffer.concat(chunks);
           return body.toString();
        });
    });


    req.end();
})

1 Answer 1

0

No response I got from any one but Genius me found a solution by self :P Just need to send response in req.end() method and it works fine

resp.on("end", function () {
    var body = Buffer.concat(chunks);
    res.send(JSON.parse(body))
});

Complete solution

app.get('/api/mailers/campaigns', async(req, res) => {
    var chunks = [];
    var options = {
        "method": "GET",
        "hostname": mailerBaseUrl,
        "path": "/api/v2/campaigns?limit=100",
        "headers": {
            "x-mailerlite-apikey": mailerApiKey
        }
    };

    var req = await http.request(options, function (resp) {
        resp.on("data", function (chunk) {
            chunks.push(chunk);
        });

        resp.on("end", function () {
            var body = Buffer.concat(chunks);
            res.send(JSON.parse(body))
        });
    });
    req.end();
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.