1

I have a empty html file that call to a js file. Inside that file I have this coded.

if (typeof web3 !== 'undefined') {
   web3 = new Web3(web3.currentProvider);
} else {
   // set the provider you want from Web3.providers
   web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:22000"));
}

web3.eth.getBlock(18, function(error, result){
if(!error)
    console.log(JSON.stringify(result));
else
    console.error(error);
});

But when I execute i get this error:

missing CORS header 'Access-Control-Allow-Origin

Any idea to solve this issue??

4
  • how do you load that HTML in the browser? do you load it from the file system? or do you load it from a locally running webserver? Commented Nov 19, 2018 at 8:05
  • form the file system. Rigth click, Open with.. Commented Nov 19, 2018 at 8:07
  • Start your Ethereum node with --jsonrpc-cors=all if it's Parity. Commented Nov 19, 2018 at 8:32
  • I disabled the cors in my web explorer. Is not the best solution but in a develop environment i can do. Thx Commented Nov 19, 2018 at 8:37

3 Answers 3

1

You have to use a webserver to serve the HTML file.

The error you're getting is because of an intended browser limitation, related to security. Have a look at this answer to find out more.

1

The response to the CORS request is missing the required Access-Control-Allow-Origin header, which is used to determine whether or not the resource can be accessed by the html file trying to access the Web3 provider.

In general this error can be prevented by configuring access control. The provider is how web3 talks to the blockchain. Providers take JSON-RPC requests and return the response. This is normally done by submitting the request to an HTTP or IPC socket based server.

0

To solve this you need to render you html file via webserver instead of the file system, to do this install an apache2 webserver in your system, then go to /var/www/html folder and in that copy you files, and to access them go to you browser and type localhost you will get you file and the error will be gone

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.