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 (ie 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-sanm-gcp-kafka-shipping-dev.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();
});
Below are the steps to solve this CORS issue in NodeJs+Google Flex Environment,
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(); });
In the app.yaml
handlers:
- url: /
static_dir: /
http_headers:
Access-Control-Allow-Origin: '*'
Try this:
1.In terminal: npm i cors --save
2.In you code:
app.use(cors());
app.options('*', cors());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.