Ad

Issue With Chrome CORS Policy

- 1 answer

I have an API to login to my system, but when sending a request with axios it gets a CORS error.

enter image description here

I have tried to install the CORS extension and reload a lot of time, but it's still not working.

enter image description here

I have then tried sending requests through https://cors-anywhere.herokuapp.com/, I get error 503 (Service Unavailable).

enter image description here

This is my function:

function getAccessToken (success, failure){
  axios.request({
    url: `${BaseConstants.REST_BASE_PATH}/rest/auth/login`,
    //`https://cors-anywhere.herokuapp.com/${BaseConstants.REST_BASE_PATH}/rest/auth/login`,
    method: "POST",
    headers: {
      Authorization: 'Basic YWRtaW51c2VyOnBhc3N3b3Jk',
      'Content-type': 'application/json',
      // 'Origin': '*',
      'Access-Control-Allow-Headers': '*',
      'Access-Control-Allow-Origin': '*',
    }
  }).then(r => {
    success(r.data);
  }.catch(r => { 
    failure(r.message);
  });
}
Ad

Answer

You can add the "cors" package as follows(express server) or can add the specific lines at the "server-side" to bypass the CORS issue.

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
app.use(cors());

// some route controllers
const customRoute = require('./customRoute.controller');

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


// Custom routes
app.use('/api/tags', customRoute);

app.use(express.static(path.join(__dirname, 'dist')));


// Catch all other routes & return index file
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

module.exports = app;

OR

'Access-Control-Allow-Methods': 'GET, POST PUT, DELETE, OPTIONS'
'Access-Control-Allow-Origin': '*'
'Access-Control-Allow-Credentials': ' true'

Hope this solves the issue. :)

Ad
source: stackoverflow.com
Ad