React giving me 403 forbidden error when making an API call

8.1k views Asked by At

I am using react to switch images using the Snoowrap Reddit api wrapper. When I use this function just using Node.js and the app module it works normally:

reddit.getSubreddit('pics').getRandomSubmission().then(function(post){
       return(post.url.toString());
     });

This is what the function looks like with my normal NodeJS app this code here works 100% fine

app.get('/getimage', function(req, res){
  r.getSubreddit(subreddit).getRandomSubmission().then(function(post){
    if(post.url.includes(".jpg") || post.url.includes(".png")){
      res.send(post.url);
      res.end();
    }
    else{
      res.send("No picture extension as .jpg .png")
      console.log("No .jpg Extension");
    }
});
  console.log("Pressed!");
});

This code here gives me an unhandled 403 rejection Error I downloaded the chrome browser CORS header extension and it fixed theAccess-Control-Allow-Origin error but now its giving me a 403 error

getPic: function() {
     reddit.getSubreddit('pics').getRandomSubmission().then(function(post){
       return(post.url.toString());
     });


   },
1

There are 1 answers

0
Joan Albert On BEST ANSWER

A common request that may result in a 403 Forbidden response is a HTTP GET request for a web page performed by a web browser to retrieve the page for display to a user in a browser window.

This maybe caused for the CORS extension, if I was you I would try to configure my server as a CORS server instead of using a chrome extension. You can use this npm

npm install cors --save 

Before your app.get(...) write a const cors = require('cors') and app.use(cors())

I maybe wrong, but give it a try!