安装axios与封装axios
安装命令
yarn add axios
安装axios
封装axios
代码如下
request.js
import axios from "axios";
export function request(config) {
const instance = axios.create({
baseURL: "http://www.tpxm.com/index.php",
timeout: 5000,
});
//请求拦截
instance.interceptors.request.use(
(config) => {
// 如果API需要认证, 在这统一设置
return config;
},
(err) => {
}
);
//响应拦截
instance.interceptors.response.use(
(res) => {
return res.data ? res.data : res;
},
(err) => {
// 如果没有授权, 去login
// 如果有错误, 在这里可以提示
}
);
return instance(config);
}
admin.js
import { request } from "./request.js";
export function getHome() {
return request({
url: "/Index/api/index",
method : "post",
})
}
export function Save(data){
return request({
url : "/Index/api/save",
method : "post",
data : data
})
}
接口
接口代码如下
<?php
namespace app\index\controller;
use app\BaseController;
use think\facade\Db;
use think\facade\Request;
class api extends BaseController
{
public function index(){
header("Access-Control-Allow-Origin: *");
$data= Db::table('bew_users')->select()->toArray();
//var_dump($data);
$datlists=[];
foreach ($data as $v){
if ($v['status']==1){
$v['status_s']="在职";
}else{
$v['status_s']="离职";
}
$v['add_time_s'] = date('Y-m-d H:m:s',$v['add_time']);
$v['last_time_s'] = date('Y-m-d H:m:s',$v['last_time']);
$datlists[]= $v;
}
echo json_encode($datlists);
}
public function save(){
if(Request::isPost()){
$data = Request::param();
$datalist = [
'account'=>$data['account'],
'name'=>$data['name'],
'password'=>md5($data['password']),
'phone'=>$data['phone'],
'status'=>$data['status'],
'add_time'=>strtotime($data['add_time']),
'last_time'=>time(),
];
$res = Db::name('bew_users')->save($datalist);
if ($res){
$rest = ['code'=>0,'msg'=>"操作成功,更新中"];
}else{
$rest = ['code'=>1,'msg'=>"操作失败,更新中"];
}
echo json_encode($rest);
}
}
}