Node - Fetch request to https://api.ipify.org/ returns {"size":0,"timeout":0}

Hi guys!

This might seem a really simple matter but I for one do not understand it right now.

I am trying to send a request to an external API to find out the user’s IP, however, I cannot seem to make it give a valid response in node.

Bellow code is in index.js

let express = require('express');
let cors = require('cors');
let bodyParser = require('body-parser');
const fetch = require('node-fetch');
var http = require('http');

var app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));

app.get('/', (req, res) => {
  res.send("Hello World!")
})

const port = process.env.PORT || 8000;

app.listen(port, () => {
  console.log('example app listening on port 8000!')
})

var headerParser = "/api/whoami";

app.get(headerParser, (req, res) => {

  fetch('https://api.ipify.org/').then(ipAddress => {
    res.json({ipaddress: ipAddress, language: req.headers['accept-language'], software: req.headers['user-agent']})
  })

})

The server responds with {“size”:0,“timeout”:0}.
What am I doing incorrectly? I am really new to node.

Thank you in advance!

1 Like

fetch returns response object, which you need to parse.

fetch("https://api.ipify.org/")
  .then((res) => res.text())
  .then((ipAddress) => {
     // do stuff with ipAddress
  });
1 Like

It was as simple as that. Inserts *slapsHerselfEmoji

Thank you very much!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.