-1
I’m having a hard time implementing a ZIP Code consultation on React
What I wish to do and the user informs the ZIP code number in the field <input/>
and automatically form fields are filled in.
What I need to do to populate the form with the ZIP code search and when trying to do it the way I implemented it presents the following error:
:3000/#/customer register:1 Access to fetch at 'https://viacep.com.br/ws/-/json/' from origin 'http://localhost:3000' has been blocked by CORS policy: 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.viacep.com.br/Ws/-/json/:1 Failed to load Resource: net::ERR_FAILED
But the search is done despite the error.
handleChange = (event) => {
const value = event.target.value;
const name = event.target.name;
this.setState({ [name] : value })
this.buscarCep();
}
buscarCep() {
if(this.state.cep.length < 9) {
return;
} else {
fetch(`https://viacep.com.br/ws/${this.state.cep}/json/`)
.then((res) => res.json())
.then((data) => {
this.state.uf = data.uf;
this.state.cidade = data.localidade;
this.state.uf = data.uf;
this.state.bairro = data.bairro;
this.state.logradouro = data.logradouro;
});
}
}
render( ){
return (
<Card>
<div className="row">
<div className="col-md-5">
<FormGroup id="inputCep" label="CEP: *" >
<InputMask id="inputCep"
className="form-control"
name="cep"
mask="99999-999"
value={this.state.cep}
onChange={this.handleChange}/>
</FormGroup>
</div>
</div>
<div className="row">
<div className="col-md-12">
<FormGroup id="inputLogradouro" label="Logradouro:" >
<input type="text" id="inputLogradouro"
className="form-control"
name="logradouro"
value={this.state.logradouro}
onChange={this.handleChange} />
</FormGroup>
</div>
</div>
<div className="row">
<div className="col-md-12">
<FormGroup id="inputBairro" label="Bairro:" >
<input type="text" id="inputBairro"
className="form-control"
name="bairro"
value={this.state.bairro}
onChange={this.handleChange} />
</FormGroup>
</div>
</div>
<div className="row">
<div className="col-md-6">
<FormGroup id="inputCidade" label="Cidade:" >
<input type="text" id="inputCidade"
className="form-control"
name="cidade"
value={this.state.cidade}
onChange={this.handleChange} />
</FormGroup>
</div>
<div className="col-md-6">
<FormGroup id="inputUf" label="UF:" >
<input type="text" id="inputUf"
className="form-control"
name="uf"
value={this.state.uf}
onChange={this.handleChange} />
</FormGroup>
</div>
</div>
</Card>
}
}
worked out .....
– novic