const express = require('express');
const catalyst = require('zcatalyst-sdk-node');
const cors = require('cors');
const app = express();
app.use(cors({
origin:"*",
credentials:true
}));
app.use(express.json());
app.post("/test", (req,res) => {
const catalystApp = catalyst.initialize(req);
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
const body=req.body;
const param=req.query;
console.log(body);
console.log(param);
res.status(200).send(JSON.stringify({"req.body": req.body,"message":"test","req.query":req.query,"req":req.method}));
});
module.exports = app;
this is the code used in the advancedio function, which is basically returning the passed post data to just test if post data is being received in request.
I am testing this api from a local html file shown below
<script>
url = "< my-function-url >"; // consider this as my advance function function url
const payload = {
"name": "test",
"phone":"9999",
};
console.log('sending',payload);
fetch(url + '/test?a=abc', {
method: 'POST',
headers: new Headers({
"Accept": "application/json",
"Content-Type": "application/json"
}),
body: payload
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.log('Error:', error);
});
</script>
and after running this js code in browser to call the function-url-api,
this is the error I am receiving
it says
Access to fetch at '{{my-function-url}}' from origin 'http://127.0.0.1:5500' 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. test.html:57 POST {{my-function-url}} net::ERR_FAILED
Error: TypeError: Failed to fetch at test.html:57:3
Need help with the server or client code, what needs to be changed or is there any other setting in catalyst from where we need to enable the CORS,
The notable thing is : if header is not passed, then the api works but POST data is not received at server. and receive the body as blank
ie
if header's content-type is commented
then the api is executed but the POST Data ie req body is not received at server, the output received in browser console is this.
Any help / Guidance would be greatly appreciated.
Jayesh Sonawane