Cliff Smith
Cliff Smith

Reputation: 45

Node.js CORs Request

I am currently attempting to use the questions API here... https://opentdb.com/api_config.php to set up a game to test out what I have learned in javascript. When I was using jquery in the browser, it was no problem and worked great. Now I am attempting to recreate the quiz with react/redux using a node.js server on localhost:3000.

Now when I make the request I get a CORS error. All of the answers on here seem to be turning off the CORs request on the server (which I have no control of).

Is there a way to work around this or am I basically stuck if I want to make this request using a browser?

Here is my current code, though I've tried it with the basic fetch command

export default function fetchQuestions(numQuestions = 5, category = 10,    difficulty = 'any') {
  const url = createURL(numQuestions, category, difficulty)
  request({
    url: url,
    json: true
  }, (error, response, body) => {
    if (!error && response.statusCode === 200) {
      console.log(body)
    }
  })
}

Upvotes: 0

Views: 2661

Answers (2)

Giorgia Sambrotta
Giorgia Sambrotta

Reputation: 1223

Is old question but maybe someone else still has this issue using opentdb API.

For me it worked when i remove the options for json.

Before i had:

await fetch(
          'https://opentdb.com/api.php?amount=10&difficulty=hard&type=boolean',
          {
            mode: 'cors',
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
            },
          }
        )

And it failed with the same CORS error had the OP.

Without specify the Content-Type, it works:

await fetch(
          'https://opentdb.com/api.php?amount=10&difficulty=hard&type=boolean',
          {
            mode: 'cors',
            method: 'GET'
          }
        )

Hope it helps someone!

Upvotes: 0

lcodegmaster
lcodegmaster

Reputation: 74

You may have to npm install the packages used below with: npm install cors npm install express

In a new file in the node folder write the code below:

var express = require("express");
var cors = require("cors");
var app = express();

var corsOptions = {
    origin: ' https://opentdb.com/api_config.php',
    optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
  }

app.use(function(req, res, next) {
    // res.header("Access-Control-Allow-Origin", "*");
    // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    // app.header('Access-Control-Allow-Origin', 'http://localhost');
    // app.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    // app.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    // app.header('Access-Control-Allow-Credentials', true);
    next();
});
///products/:id
  app.get('/helloworld', cors(corsOptions), function (req, res, next) {
    res.json({msg: 'This is CORS-enabled for only example.com.'});
  })

  app.listen(3000, function() {
      console.log("CORS-enabled web server listening on port 3000");
  });

var response_text;

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
//Get the html of the website
function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        // Check if the XMLHttpRequest object has a "withCredentials" property.
        // "withCredentials" only exists on XMLHTTPRequest2 objects.
        xhr.withCredentials = true;
        xhr.open(method, url, true);
        xhr.send();    
    } else if (typeof XDomainRequest != "undefined") {

      // Otherwise, check if XDomainRequest.
      // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
      xhr = new XDomainRequest();
      xhr.open(method, url);
      xhr.send();
    } else {

      // Otherwise, CORS is not supported by the browser.
      xhr = null;

    }
    return xhr;
  }

  var url = "https://opentdb.com/api_config.php";

  var xhr = createCORSRequest('GET', url);
  if (!xhr) {
    throw new Error('CORS not supported');
  }

  xhr.onload = function() {
    response_text = xhr.responseText;
    console.log(response_text);
    console.log(values);
    // process the response.
   }

   xhr.onerror = function() {
     console.log('There was an error!');
   }

Then cd to the file directory in the terminal and write: $ node filename.js

It will then be listening on http://localhost:3000/helloworld Hope this works.

Upvotes: 1

Related Questions