Skip to content
Advertisement

Sending Headers with a GET request to Third Party API

I am trying to build a small full-stack application, where my frontend code will only interact with my backend, and the backend will call Third Party API to fetch results and then do whatever it wants with it.The third party API I am using requires an Accept , app_id and app_key headers for any request.

I can send a GET request directly to my third party API with Postman and fetch results just fine, but when I try to send GET request through my NodeJS API, I am receiving status 403 instead . I am using node-fetch for this purpose.

The API I am using is Oxford Dictionary API

Here is the code for my index.js file

require('dotenv').config();

const express = require('express');
const router = require('./routes/router');
const cors = require('cors');
const app = express();

const port = process.env.PORT || '5000';
const host = process.env.HOST || 'localhost';

app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(router);

app.listen(port, () => console.log(`server is up and running at http://${host}:${port} `));

Here is the code for my router.js file.

const express = require('express')
const fetch = require('node-fetch');

const router = express.Router();
const BASE_URL = process.env.BASE_URL;
const fields = 'definitions';

router.get('/', (req, res) => {
    res.json({
        status: "successfully connected !"
    });
});

router.post('/create', (req, res) => {

    console.log(req.body);
    console.log(req.body.word);
    const url = `${BASE_URL}entries/en-gb/${req.body.word}?fields=${fields}&strictMatch=true`;
    const newHeaders = {
        "Accept": "application/json",
        "app_id": process.env.APP_ID,
        "app_key": process.env.API_KEY
    }

    fetch(url, { method: 'GET', headers: { newHeaders } })
        .then((results) => {
            console.log(results);
        }).then(results => {
            res.json(results);
        }).catch((err) => { console.log(err) });

});

module.exports = router;

Following is the results i am receiving :-

Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: PassThrough {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      [Symbol(kCapture)]: false,
      [Symbol(kTransformState)]: [Object]
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    url: 'https://od-api.oxforddictionaries.com/api/v2/entries/en-gb/swim?fields=definitions&strictMatch=true',
    status: 403,
    statusText: 'Forbidden',
    headers: Headers { [Symbol(map)]: [Object: null prototype] },
    counter: 0
  }
}

Rest Assured, the environment variables are all set with accurate values.

I want to be ale to attach headers and send a GET request to third party API and successfully fetch results. Also, I want to be able to send those results back to my client.

I have few questions regarding my code.

  1. Is it correct to use fetch inside of an express route ?
  2. If yes, why is this returning status 403 ?
  3. If no, what is the correct way to achieve this ?
  4. What does this headers: Headers { [Symbol(map)]: [Object: null prototype] }, mean ?

I am a newbie in web development, so this question might seem stupid to some veterans here but please help me out. I have read the following resources but none of them helped me:-

Accessing [Symbol(Response internals)] from JSON response

Node-Fetch API GET with Headers

How to fetch from third party API inside backend route?

Edit:

I used app-id and app-key instead of app_id and app_key which I have corrected now but the problem isn’t yet solved.

Advertisement

Answer

As I mentioned in a comment, you had a typo:

headers: { newHeaders }newHeaders is already an object, so use headers: newHeaders.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement