CORS error for missing Access-Control-Allow-Origin in preflight response header with NodeJs endpoint

I need to receive the privileges from Server for the Access-Control-Allow-Origin: *  in the response header. Keep receiving CORS error for some endpoints: 'Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.'

 

The setup below works for some endpoint but not all of endpoints, here is the one that isn't working:

- Use OAuth2.0 for authorization, successful response in the POSTMAN test with the access token

- Pass the access token (configure with the domain, client id, audience, redirectUri) in the header for the axios call

 

// get token 
auth0Client = new Auth0Client({
   redirectUri: window.location.origin,
   audience: `https://${process.env.REACT_APP_AUTH_DOMAIN}/api/v2/`,
   client_id: process.env.REACT_APP_AUTH_CLIENTID,
   domain: process.env.REACT_APP_AUTH_DOMAIN
})
const token = await auth0Client.getTokenSilently({
  audience: `https://${process.env.REACT_APP_AUTH_DOMAIN}/api/v2/`
});

// here is the axios call
axios.get(shippingServicesApi.shippingRates, { headers: { Authorization: `Bearer ${token}`}})
   .then(response => {
      setShippingRates(response.data);
   })
   .catch(e => console.log(e));

 

- At NodeJs endpoint, allow CORS policy through the function

 

// Retrieves one shipping rate based on a requested ID, or all rates without a passed ID
const exportFunction = async (req, res) => {

    res.set('Access-Control-Allow-Origin', '*');
    res.set('Access-Control-Allow-Methods', '*');

    const connection = await makeConnection();
    connection.connect();
    
    const shippingRateId = req.query.shippingRateId;

    if (req.method === 'OPTIONS') {
        // Send response to OPTIONS requests
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', '*');
        res.header('Access-Control-Allow-Headers', '*');
        res.header('Access-Control-Max-Age', '3600');
        res.status(204).send('');
    } else {
    //If an ID was passed, find the rate with that ID
    if (shippingRateId !== undefined) {
        connection.query(`SELECT * FROM ShippingRate WHERE ShippingRateId = ${shippingRateId}`, (error, response) => {
            res.header('Access-Control-Allow-Origin', '*');
            res.header('Access-Control-Allow-Headers', '*');
            res.header('Access-Control-Allow-Methods', '*');  
            if(error) { 
                res.status(400).send(error);
            }
            res.status(200).send(response);
        })
    }

    //If no ID is passed, return all shipping rates
    else {
        connection.query(`SELECT * FROM ShippingRate `, (error, response) => {
            res.header('Access-Control-Allow-Origin', '*');
            res.header('Access-Control-Allow-Headers', '*');
            res.header('Access-Control-Allow-Methods', '*');  
            if(error) { 
                res.status(400).send(error);
            }
            res.status(200).send(response);
        })
    }}
    connection.end();
};

 

setting in endpoint.yaml config for GCP Api gateway

 

swagger: '2.0'
host: {gateway url here}
x-google-endpoints:
- name: {gateway url here}
  allowCors: True
securityDefinitions:
  auth0_jwt:
    authorizationUrl: {auth0 url}/authorize
    flow: implicit
    type: oauth2
    x-google-issuer: {auth0 url}
    x-google-jwks_uri: {auth0 url}/.well-known/jwks.json
    x-google-audiences: {auth0 url}/api/v2/
schemes:
  - https
produces:
  - application/json
path:
 /shippingRates:
  options:
      summary: handleoptions for shippingRates
      operationId: handleoptionsshippingRates
      x-google-backend:
        address: {Cloud Function Trigger URL}
      security:
        - auth0_jwt: []
      responses:
        '200':
          description: A successful response
          schema:
            type: object   
    post:
      summary: create a shipping rate
      operationId: createShippingRate
      x-google-backend:
        address:  {Cloud Function Trigger URL}
      security:
        - auth0_jwt: []
      responses:
        '200':
          description: A successful response
          schema:
            type: string
    delete:
      summary: delete a shipping rate
      operationId: deleteShippingRate
      x-google-backend:
        address:  {Cloud Function Trigger URL}
      security:
        - auth0_jwt: []
      responses:
        '200':
          description: A successful response
          schema:
            type: string
    get:
      summary: Get shipping rates
      operationId: getShippingRates
      x-google-backend:
        address:  {Cloud Function Trigger URL}
      security:
        - auth0_jwt: []
      responses:
        '200':
          description: A successful response
          schema:
            type: string
      parameters:
        - name: shippingRateId
          in: query
          description: shippingRate Id
          type: integer
          format: int64
    patch:
      summary: update shipping rates
      operationId: updateShippingRate
      x-google-backend:
        address:  {Cloud Function Trigger URL}
      security:
        - auth0_jwt: []
      responses:
        '200':
          description: A successful response
          schema:
            type: string

 

 

 

 

0 1 4,824
1 REPLY 1

Does this CORS issue resolved? I am also struggling with this and haven't found any resolutionary stepstill now? If so could you please add detailed resolution steps as I am very new to cloud and very much disappointed due to GCF behaviour?