lourdu rajan
lourdu rajan

Reputation: 379

Node Js Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response

After adding custom header(named as 'RBR') in node API and hosting as Google Endpoint in Flex Environment,getting CORS error. This node API called from Angular code. We have hosted both Angular and Node code as Google Flex Environment. API has three parameters two header value and one body value. 1.Authorization (i.e. OAuth JWT token) 2. RBR (we have custom repository for Authorization) 3. body value - Json type.

In the openapi.yaml file we have added below lines for CORS issue.

x-google-endpoints:
    - name: "backend-dot-myproject.appspot.com"
    allowCors: "true"

In node js we have added below code for CORS issue.

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers",
    "Access-Control-Allow-Headers,Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,authorization,rbr");
  if (req.headers.origin) {
    res.header('Access-Control-Allow-Origin', req.headers.origin);
  }
  if (req.method === 'OPTIONS') {
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE");
    return res.status(200).json({});
  }
  res.setHeader('Access-Control-Allow-Credentials', true);
  next();
});

Upvotes: 0

Views: 3326

Answers (2)

lourdu rajan
lourdu rajan

Reputation: 379

Below are the steps to solve this CORS issue in NodeJs+Google Flex Environment,

  1. Update your middleware code

      app.use((req, res, next) => {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers",
        "Origin, X-Requeted-With, Content-Type, Accept, Authorization, RBR");
      if (req.headers.origin) {
        res.header('Access-Control-Allow-Origin', req.headers.origin);
      }
      if (req.method === 'OPTIONS') {
        res.header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE");
        return res.status(200).json({});
      }
      next();
     });  
  2. In the app.yaml

handlers:
    - url: /
      static_dir: /
      http_headers:
        Access-Control-Allow-Origin: '*'

Upvotes: 2

sohamdodia
sohamdodia

Reputation: 377

Try this:

1.In terminal: npm i cors --save

2.In you code:

app.use(cors());
app.options('*', cors());

Upvotes: 1

Related Questions