-1

Trying to send an axios post request from a Vue app (localhost) to my nodejs API (both localhost and heroku).
There are no issues receiving the response if the request is sent without data or headers, but as soon as I add them I get the following error:

Access to XMLHttpRequest at 'https://myapp.herokuapp.com/myendpoint' from origin 'http://localhost:8080'
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested resource.

I have tried different options, both server and client side, as suggested on similar questions but had no success.

Client Request:

        const apiUrl = 'https://myapp.herokuapp.com/myendpoint'
        //const apiUrl = 'http://localhost:5000/myendpoint'
        
        const token = Buffer.from(`${this.userid}:${this.password}`).toString('base64')
        const data = {
          'mydata': 'some data'
        }

        axios.post(apiUrl, data, {
          headers: {
            Authorization: "Basic " + token 
          }
        }).then( res => {
          console.log(res)
        }).catch( err => {
          console.log(err)
        })

Server Endpoint:

app.post("/myendpoint", (req, res) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

    res.send('This is the API\'s response')    
})

Some of the answers I tried:
Response to preflight request doesn't pass access control check
Nodejs Express CORS issue with 'Access-Control-Allow-Origin'
https://www.moesif.com/blog/technical/cors/Authoritative-Guide-to-CORS-Cross-Origin-Resource-Sharing-for-REST-APIs/
CORS authorization issue while using axios
How to send authorization header with axios

Lera
  • 3
  • 2

1 Answers1

-1

I think it is better if you define your cors using a global middleware. First off, install cors by using npm i cors.

Then, I'll show an example of how that package could be used.

const express = require('express');
const cors = require('cors');

const app = express();

app.use(cors());

// your routes and things here...

Then, ensure that your front-end also uses withCredentials set to true in the axios request. This is done to ensure that the header is being sent properly.

axios.post(apiUrl, data, {
  headers: {
    Authorization: "Basic " + token 
  },
  withCredentials: true,
}).then(() => ...);

Sometimes, if you define Access-Control-* manually, you might forget something. That's why I recommend you to use cors.

Nicholas D
  • 1,729
  • 1
  • 4
  • 16
  • Thanks for the answer, don't know why it got downvoted... I needed to set some cors options as well: ` const corsOptions = { origin: 'http://localhost:8080', credentials: true, methods: ["POST"], maxAge: 3600 } app.use(cors(corsOptions)) ` – Lera Mar 16 '21 at 09:20