aamadeo aamadeo - 1 month ago 20
Javascript Question

Javascript - Querying VoltDB api with fetch

I'm trying to query a VoltDB using its api:

const url = 'http://server:8080/api/1.0/'
const queryParam = encodeURIComponent('select * from table')
const queryURL = url + `?Procedure=@AdHoc&Parameters=['${queryParam}']&jsonp=console.log`

fetch(queryURL).then( response => {
response.text().then( text => console.log(text) )
})


With that code throws an "No Access-Control-Allow-Origin" error.
If I change the fetch call to this:

fetch(queryURL, { mode: 'no-cors').then( response => {
response.text().then( text => console.log(text) )
})


It does nothing

Answer

This is a browser security feature. If you are serving a web page from one url and within the page you have embedded url calls to another host or port, then the browser won't allow this.

One way to get around this is to add a proxy to your web server, so it can make the calls to port 8080, and pass the responses back to the web page from the same origin.

You may see some answers on Stack Overflow about using CORS to get around this error, but that requires changing the headers that VoltDB uses on port 8080, so that's not something you can do yourself, and we have no plans to do that.

Another solution is to use the voltdb.js file provided in some of our demos, such as the NBBO demo dashboard: https://github.com/VoltDB/voltdb/tree/master/examples/nbbo/web

I think this uses low-level javascript to open a socket to make the HTTP call without using XMLHttpRequest, so it avoids the No Access-Control-Allow-Origin error.

In the example, the code that is specific to the NBBO example is in demo.js, voltdb-dashboard.js contains code that is common to various example dashboards, and voltdb.js is the base library that provides access to call procedures asynchronously.