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??

Aniket
  • 3,545
  • 2
  • 20
  • 42
UnexpectedCharacter
  • 852
  • 1
  • 11
  • 30

3 Answers3

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.

Tudor Constantin
  • 2,625
  • 1
  • 9
  • 15
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.

Gokul Alex
  • 390
  • 1
  • 14
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

vaibnak
  • 101
  • 1