郵便番号から住所取得
/郵便番号取得APIで利用したいがJavaScriptで取得するとクロスドメインにかかってしまい失敗
代わりにphpで取得
↓ yubin.php
<?php
$zip = $_GET['zip'];
$url = 'https://zip-cloud.appspot.com/api/search?zipcode='.$zip;
$data = file_get_contents($url);
$data = json_decode($data)->results[0];
//print_r($data);
$addr = $data->address2. $data->address3;
$res = array('pref'=>$data->address1, 'addr'=>$addr);
//print_r($res);
echo json_encode($res);
?>
Vue
zipGet: function(){
let url = 'yubin.php?zip=' + this.zip;
fetch(url)
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
this.lists = data;
})
.catch(error => {
console.log(error);
});
}
以下は、ブラウザによってクロスドメインの制限にかかってしまい取得できない。。^_^;
methods: {
checkZip: function(){
//住所を取得
let url = 'https://api.zipaddress.net/?zipcode=' + this.zip;
fetch(url) //Fetch API
.then( response => {
return response.json();
})
.then( json => {
this.pref = json.data.pref;
this.addr = json.data.address;
})
.catch( (err) => {
this.pref = '';
this.addr = '';
});
}
}