Help Require Node

Asked

Viewed 58 times

0

It all starts when I try to receive a JSON from the CNPJ API, I am using Node and consequently NPM and thus using AXIOS to receive JSON. Okay, all right until then. However, I want to take the json information and assign it to form fields (same form I receive the CNPJ). And I came across the following problem, to use the AXIOS I need to perform a require to load the module, however I can’t do it inside a file . js uploaded by browser, can anyone help me in how to fix this or suggest another way to reach my goal ?

Html

   <label for="cnpj"><div >CNPJ: </div></label>
   <input name="cnpj" id="cnpj" type="text" onblur="getCnpj(this.value)">

   <label for="endereco"><div >Endereco: </div></label>
   <input placeholder="Digite o endereço" id="endereco" type="text">

   <script type="text/javascript" src="../js/cnpj.js"></script>
Javascript

const getCnpj = (cnpj) => {
    const axios = require('axios');
    axios.get('https://www.receitaws.com.br/v1/cnpj/'+cnpj)
    .then(function (response) {
        if (response.data.status == "ERROR")
            alert("CNPJ Inexistente");
        else{
          document.getElementById('endereco').value = response.data.endereco;
        }    

    })
    .catch(function (error) {
        console.log(error);
        alert("Erro ao buscar por Cnpj");
    });
}
  • Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).

2 answers

0

The Node is a different context from your client page. The require by itself works only on Node. To use on the customer you only need to import the axios in his HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>

  • It is worth detailing that in this case he will not use the require.

  • @Coldmeson_06 I don’t think it’s necessary. require in the node, are different contexts

0

This is a matter of build system, what you want to do is "compile" your JS code before running it in the browser, in your case the Browserify should be enough since it requires almost 0 configuration, but it is worth taking a look at the Babel also, but setting up Babel is already a topic by itself...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.