nerdcoder
nerdcoder

Reputation: 409

Nodejs return data after get request inside a post request

i'm trying to pass get request answer to the post request but can't, can someone help me please?

var app = require('express')();
var http = require('http').Server(app);
var bodyParser = require('body-parser');
var request = require('request');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

http.listen(9999, function() {
  console.log('listening...');
});

app.post('/bot',function(req,res){
  var apiurl = 'https://apiURI'
  request(apiurl, function(error,response,body){
    res.send(body)
  })
}

when i receive the api answer should send to client who make the post request with res.send

error: Can't set headers after they are sent.

Upvotes: 0

Views: 3172

Answers (1)

nerdcoder
nerdcoder

Reputation: 409

Error solved, deleting the end() method outside the get request due to it's a async request (my mistake)

var app = require('express')();
var http = require('http').Server(app);
var bodyParser = require('body-parser');
var request = require('request');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

http.listen(9999, function() {
  console.log('listening...');
});

app.post('/bot',function(req,res){
  var apiurl = 'https://newsapi.org/v1/articles?source=techcrunch&apiKey=72cc6a313e2b4fb3af09e4593ee06fbc'
  request(apiurl, function(error,response,body){
    res.send(body)
  })
  //res.end()
})

Upvotes: 1

Related Questions