PS: 聚合接口上描述的是成语大全,其实只是以用户查找字为开头的成语而已。先上演示效果:
1: VUE 前端代码
<template>
<div class="content">
<!--
请求地址:http://apis.juhe.cn/idiomJie/query
请求参数:wd=%E9%80%BC&size=&is_rand=1&key=b1bcc301******24cdbe1b
请求方式:GET
参数名 类型 是否必填 说明 值
wd string 是 查询的成语,如:一心一意 逼
size int 否 返回的结果数量限制,如:5。 默认所有
is_rand int 否 是否随机返回结果,1:是 2:否。 默认2
{
"reason":"success",
"result":{
"last_word":"逼",
"data":[
"逼良为娼",
"逼上梁山",
"逼人太甚",
"逼不得已"
],
"total_count":4
},
"error_code":0
}
从返回结果上看,这并不是成语接龙,而是查询开头为 查询字的 成语
1: 查询字, 如果查询结果的 total_count < 1 ,返回没有结果,不然全部显示出来
-->
<el-card :span="12">
<div class="queryEle">
<el-input placeholder="请输入开头字" v-model="queryWord" class="queryIpt"></el-input>
<el-button type="success" plain @click="queryIdioms">查询</el-button>
</div>
<h1>{{ beforeQueryS }}<span class="heightLight">{{ midQueryS }}</span>{{ endQueryS }}</h1>
<ol class="idiomsOl">
<li v-for="(d, index) in data" :key="index" >
<span>{{ index + 1 }} :</span>
<span class="idiom">{{ d }}</span>
</li>
</ol>
</el-card>
</div>
</template>
<script>
export default {
name: 'idioms',
mounted: function () {
this.getData()
},
data () {
return {
apiUrl: '/api_8',
queryWord: '', // 需要查询的开头字
beforeQueryS: '输入开头字,查询相关',
midQueryS: '',
endQueryS: '字开头的成语',
data: [ '逼良为娼', '逼上梁山', '逼人太甚', '逼不得已' ]
}
},
methods: {
getData: function () { // 获取数据
console.log('I am getting')
this.$axios({
url: this.apiUrl,
params: {
queryWord: this.queryWord
},
methods: 'get'
}).then(res => {
if (res.data.error_code === 0) {
console.log(res.data.result)
this.data = res.data.result.data
} else {
console.log('something wrong')
}
}).catch(err => {
console.log(err)
})
},
queryIdioms: function () { // 查询按钮
let queryW = this.queryWord.trim()
this.queryWord = queryW
if (queryW === '' || queryW === null) {
this.$alert('请输入有效字', '错误指令', {
confirmButtonText: 'OK'
})
} else {
this.beforeQueryS = '以下是您查询的以'
this.midQueryS = this.queryWord
this.endQueryS = '为开头的成语'
this.getData()
}
}
}
}
</script>
<style scoped>
.content {
margin-left: 12%;
text-align: center;
}
.queryEle {
display: flex;
justify-content: center;
margin: 1rem 0;
}
.queryEle .queryIpt {
width: 8rem;
margin-right: 2rem;
}
h1 {
margin-bottom: 1rem;
}
.idiomsOl {
font-family: '楷体';
font-weight: bolder;
font-size: 2.5rem;
}
.heightLight {
color: red;
}
/* 每个成语的字体颜色,JS就不写了,CSS简单 */
.idiomsOl li:nth-child(1) { color: darkorchid; }
.idiomsOl li:nth-child(2) { color: coral; }
.idiomsOl li:nth-child(3) { color: darkcyan; }
.idiomsOl li:nth-child(4) { color: hotpink; }
.idiomsOl li:nth-child(5) { color: peachpuff; }
.idiomsOl li:nth-child(6) { color: aqua; }
.idiomsOl li:nth-child(7) { color: lightgreen; }
.idiomsOl li:nth-child(8) { color: magenta; }
.idiomsOl li:nth-child(9) { color: black; }
.idiomsOl li:nth-child(10) { color: blue; }
.idiomsOl li:nth-child(11) { color: fuchsia; }
.idiomsOl li:nth-child(12) { color: gray; }
.idiomsOl li:nth-child(13) { color: green; }
.idiomsOl li:nth-child(14) { color: lime; }
.idiomsOl li:nth-child(15) { color: maroon; }
.idiomsOl li:nth-child(16) { color: navy; }
.idiomsOl li:nth-child(17) { color: olive; }
.idiomsOl li:nth-child(18) { color: purple; }
.idiomsOl li:nth-child(19) { color: red; }
.idiomsOl li:nth-child(20) { color: silver; }
.idiomsOl li:nth-child(21) { color: teal; }
.idiomsOl li:nth-child(22) { color: white; }
.idiomsOl li:nth-child(23) { color: yellow; }
</style>
2: VUE 前端代理解决跨域
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api_1': {
target:'http://www.chaxun.com/joke', // 你请求的第三方接口
changeOrigin:true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
pathRewrite:{ // 路径重写,
'^/api_1': '/api_1' // 替换target中的请求地址,也就是说以后你在请求 target 的地址的时候直接写成 /api_1 即可。
}
},
'/api_2': {
target: 'http://www.chaxun.com/constellation',
changeOrigin: true,
pathRewrite: {
'^/api_2': '/api_2'
}
},
'/api_3': {
target: 'http://www.chaxun.com/weather',
changeOrigin: true,
pathRewrite: {
'^/api_3': '/api_3'
}
},
'/api_4': {
target: 'http://www.chaxun.com/news',
changeOrigin: true,
pathRewrite: {
'^/api_4': '/api_4'
}
},
'/api_5': {
target: 'http://www.chaxun.com/videos',
changeOrigin: true,
pathRewrite: {
'^/api_5': '/api_5'
}
},
'/api_6': {
target: 'http://www.chaxun.com/driverlicense',
changeOrigin: true,
pathRewrite: {
'^/api_6': '/api_6'
}
},
'/api_7': {
target: 'http://www.chaxun.com/today_in_history',
changeOrigin: true,
pathRewrite: {
'^/api_7': '/api_7'
}
},
'/api_8': {
target: 'http://www.chaxun.com/idioms',
changeOrigin: true,
pathRewrite: {
'^/api_8': '/api_8'
}
}
},
// Various Dev Server settings
host: '0.0.0.0', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
// Use Eslint Loader?
// If true, your code will be linted during bundling and
// linting errors and warnings will be shown in the console.
useEslint: true,
// If true, eslint errors and warnings will also be shown in the error overlay
// in the browser.
showEslintErrorsInOverlay: false,
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
/**
* Source Maps
*/
productionSourceMap: true,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}
3: TP5 接口写入
<?php
namespace app\index\controller;
use app\index\controller\HttpRequest;
use think\Route;
use think\Request;
class Api8 {
/*
*/
const CONST_KEY = "自己聚合申请的API KEY"; // 聚合申请的成语接龙接口,其实是开头字的成语,非成语接龙
public function test()
{
return "This query idioms control is working.";
}
public function index()
{
// 下面先返回本地 json 数据
// $content = file_get_contents('./testjson/test8.json');
// $data = json_decode($content);
// return json($data);
$url = "http://apis.juhe.cn/idiomJie/query";
$req = request() -> param();
(isset($req['queryWord']) && (trim($req['queryWord']) !== '')) ? ($queryWord = $req['queryWord']) : ($queryWord = '意');
if ($queryWord === '意') { // 用户输入为空或者 意, 都返回本地 json 文件
$content = file_get_contents('./testjson/test8.json');
$data = json_decode($content);
return json($data);
} else {
$url = 'http://apis.juhe.cn/idiomJie/query';
$params = [
"wd" => $queryWord
];
$paramsString = http_build_query($params);
$httpReq = new HttpRequest;
$data = $httpReq -> httpRequest($url, $paramsString."&key=".self::CONST_KEY);
return $data;
}
}
}
4: TP5 HTTP 请求封装
<?php
namespace app\index\controller;
class HttpRequest {
public function index () {
return "constellation api";
}
/**
* 发起网络请求函数
* @param String $url 请求的URL
* @param bool $params 请求的参数内容
* @param int $isPost 是否POST请求
* @return bool|string 返回内容
*/
public function httpRequest($url, $params = false, $isPost = 0){
$httpInfo = [];
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36'); // 浏览器代理信息,我这里设置的自己的浏览器
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); // 连接的等待时间, 3秒
curl_setopt($ch, CURLOPT_TIMEOUT, 12); // 函数最长的执行时间
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将 curl_exec() 获取的信息以字符串返回,而不是直接输出
if ($isPost) {
curl_setopt($ch, CURLOPT_POST, true); // true 表示 post 请求
curl_setopt($ch, CURLOPT_POSTFIELDS, $params); // post 的请求数据的处理
curl_setopt($ch, CURLOPT_URL, $url); // 设置访问的 URL
} else {
if ($params) {
curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
} else {
curl_setopt($ch, CURLOPT_URL, $url);
}
}
$reponse = curl_exec($ch);
if ($reponse === FALSE) {
return false; // echo "cURL Error: ".curl_error($ch);
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$httpInfo = array_merge($httpInfo, curl_getinfo($ch));
curl_close($ch);
return $reponse;
}
}
?>
5: TP5 路由设置
return [
'__pattern__' => [
'name' => '\w+',
],
'[hello]' => [
':id' => ['index/hello', ['method' => 'get'], ['id' => '\d+']],
':name' => ['index/hello', ['method' => 'post']],
],
'joke' => ['index/Api1/joke', ['method' => 'get']],
'constellation' => ['index/Api2/index', ['method' => 'get']],
'weather' => ['index/Api3/index', ['method' => 'get']],
'news' => ['index/Api4/index', ['method' => 'get']],
'videos' => ['index/Api5/index', ['method' => 'get']],
'driverlicense' => ['index/Api6/index', ['method' => 'get']],
'today_in_history' => ['index/Api7/index', ['method' => 'get']],
'idioms' => ['index/Api8/index', ['method' => 'get']]
];
6: 来个测试的 JSON 文件
{
"reason": "success",
"result": {
"last_word": "意",
"data": [
"意往神驰",
"意致纵横",
"意兴阑珊",
"意在笔外",
"意气相亲"
],
"total_count": 5
},
"error_code": 0
}
TP5后端,VUE前端请求聚合数据过去的今天
TP5后端,VUE前端请求聚合数据新闻接口
TP5后端,VUE前端请求聚合数据笑话大全接口
TP5后端,VUE前端请求聚合数据天气接口
TP5后端,VUE前端请求聚合数据热门视频接口
TP5后端,VUE前端请求聚合数据驾照题库