1

I am using the cors npm package to solve the cors issue but with no avail. This was working before but when I switched over to my development environment, I keep getting this error:

Access to fetch at 'https://carside.firebaseapp.com/sendsmstoconsumer' from origin 'https://carside.web.app' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

This is how my functions code is set up:

const functions = require('firebase-functions')
const express = require('express')
const app = express()
const accountSid = 'SECRET'
const authToken = 'SECRET'
const client = require('twilio')(accountSid, authToken)
const cors = require('cors')

// Enable cors for everything
// TODO: Re-enable cors at a later date 
// src: https://www.npmjs.com/package/cors
app.use(cors())

app.post('/sendsmsverificationmessage', cors() ,(request, response) => {

    client.verify.services('SECRET')
        .verifications
        .create({to: request.body.phone, channel: 'sms'})
    .then(verification => {
        response.send("Your verification code has been sent to your phone!" )
    });
})

exports.app = functions.https.onRequest(app)

Zubair Amjad
  • 621
  • 1
  • 10
  • 29

2 Answers2

2

You need:

const cors = require('cors')({origin: true});

See also:

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
0

It looks alright to me, maybe check that you have restarted the express server since making the change. Otherwise, I don't use the cors package, instead I use the snippet from https://enable-cors.org/server_expressjs.html The * gives everything access, but it can be replaced by the specific domain that you want to give access to.

EDIT: Also, you are using cors() twice. Once in app.use() and again in your route. I don't think that would cause cors to not work, but it is unnecessary.

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
Jon Baltz
  • 202
  • 1
  • 7
  • I got rid of the cor and started using app.use(cors) and it still does't work. This is the error I am getting now "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource." – Zubair Amjad Jan 02 '21 at 06:04