I have to execute a knime workflow from javascript. I am using rest api for this purpose. Please find the js snippet below:
function rest_api_call() {
let url = 'https://knime.zf-world.com/knime/rest/v4/repository/AIT/Test/simple_restapi:execution';
let username = 'xxxxx';
let password = 'xxxxx';
let headers = new Headers();
headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));
fetch(url, {method:'POST',
headers: headers,
credentials: 'include'
})
.then(response => response.json())
.then(json => console.log(json));
}
But when I am executing this function (calling from another html file), I am getting following CORS error:
Access to fetch at 'https://knime.zf-world.com/knime/rest/v4/repository/AIT/Test/simple_restapi:execution' from origin 'null' 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.`
I did not want to change anything in the server side, so I added following line into my code: process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
This is really unsafe and should not be used in the production environment, but for testing porposes it works for me.
Complete code:
function rest_api_call() {
var response = '';
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var http = require('https');
const header = {
'hostname': 'knime-test.com',
'port': 8080,
'path': '/rest/v4/repository/Test/simple_restapi:execution',
'auth': 'user:pass'
};
var request = http.request(header, function (response) {
response = 'STATUS: ' + response.statusCode;
console.log(response);
});
request.end();
}
rest_api_call();