Home > Blockchain >  How to solve CORS error "No 'Access-Control-Allow-Origin' header is present" in
How to solve CORS error "No 'Access-Control-Allow-Origin' header is present" in

Time:09-24

I have developed a MERN stack project which needs OAuth token from facebook. In order to get the access code from facebook, I am calling the backend api getAccessCode. Below is my api impementation,

const bodyParser = require('body-parser');
const express = require('express');
const router = require('express').Router();
const {FB} = require('fb')
const QueryString = require('query-string')
const app = express();
const env = require('dotenv').config()
const constants = require('../common/constants')

const cors = require('cors')

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

app.use(cors())
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested With, Content-Type, Accept');
    next();
});

router.route('/getAccessCode').post((request, response)=> {

    const stringifiedParams = QueryString.stringify({
        client_id : process.env.CLIENT_ID,
        redirect_uri : process.env.REDIRECT_URI,
        scope : [constants.EMAIL, constants.USER_PHOTOS],
        response_type : constants.CODE,
        auth_type : constants.RE_REQUEST,
        display : constants.POPUP
    })

    const fbURL = process.env.ACCESS_CODE_URL   stringifiedParams


    return response.redirect(fbURL)
})

By following several similar questions, I have found that I need to enable CORS. Therefore, I enabled the cors policy as in the above code. But still when I send a post request from my frontend, it gives the following error,

Access to XMLHttpRequest at 'https://www.facebook.com/v11.0/dialog/oauth?auth_type=rerequest&client_id=111111111111111&display=popup&redirect_uri=http://localhost:3000/&response_type=code&scope=email&scope=user_photos' (redirected from 'http://localhost:8000/fb/getAccessCode') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
www.facebook.com/v11.0/dialog/oauth?auth_type=rerequest&client_id=11111111111111111&display=popup&redirect_uri=http://localhost:3000/&response_type=code&scope=email&scope=user_photos:1 Failed to load resource: net::ERR_FAILED
createError.js:16 Uncaught (in promise) Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:84)

Below is my request which is written in frontend,

axios.post("http://localhost:8000/getAccessCode")

Can someone please help me to solve this issue? Thanks in advance!

CodePudding user response:

On frontend you're making a request with axios. axios makes the request under the hood, i.e. your browser's Location header is not set. So when you redirect the request, it turns into a cross-site request, because you're still on the same domain as you were before, while trying to request data from facebook via javascript.

What you can do is either:

  1. Not use axios request to fetch the URL, you can build the URL in the frontend and navigate user to that URL (with <a href= or a button or programmatically, whatever you prefer).

OR

  1. If you must fetch the URL string from backend, then just do that, nothing more. No need to redirect the request from the backend. So in your code, express should return res.status(200).json({ fbURL });. And in your axios's response handler, you should programmatically navigate the user to the facebook page for authentication: window.location = res.data.fbURL;
  • Related