Vue使用axios出现options请求方法
陈小坏 人气:0以下代码如果需要在你本地跑起来:
Ⅰ.需要apache服务,并把php代码丢进去指定位置
Ⅱ.将下面http://www.test.comhttps://img.qb5200.com/download-x/day05/jiekou.php地址,改成自己指定位置的域名或ip
1.从一段简易代码说起
前端代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <!-- 导入axios --> <script src="https://unpkg.com/axioshttps://img.qb5200.com/download-x/dist/axios.min.js"></script> </head> <body> <!-- POST 请求 --> <form method="post"> <p>用户名:<input id="username" type="text" name="username" value="admin"> </p> <br /> <p>密 码:<input id="password" type="text" name="password" value="123456"> </p> <br /> <p><input id="btn" type="submit" value="登录" /></p> </form> </body> <script> document.getElementById("btn").onclick = function () { //获取用户输入的登录信息 let username = document.getElementById('username').value; let password = document.getElementById('password').value; //不处理的数据对象 let data = { username: username, password: password }; console.log(data);//{username: "admin", password: "123456"} //阻止submit默认行为:表单提交刷新页面 event.preventDefault(); //提交请求获取响应数据 axios.post("http://www.test.comhttps://img.qb5200.com/download-x/day05/jiekou.php", data).then(res => { console.log(res); }).catch(err => { console.log(err); }) } </script> </html>
php接口代码
<?php // 制定允许其他域名访问 header("Access-Control-Allow-Origin:*"); // 允许的响应类型 header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH'); // 响应头设置 header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization"); // 获取form表单值 $username = $_POST['username']; $password = $_POST['password']; // 判断form表单中key if(isset($_POST['username']) && isset($_POST['password'])){ // 判断username和password if($username == "admin" && $password == "123456"){ $result = array("success" => 1, "code" => 101, "data" => array("username" => $username, "password" => $password)); }else{ $result = array("success" => 0, "code" => 103, "data" => null); } }else{ $result = array("success" => 0, "code" => 100, "data" => null); } // 将错误信息(数组)转换成json类型,返回前端 echo(json_encode($result)); ?>
结果:运行失败,无法获取响应数据
2.解决:
方法Ⅰ.引入qs模块处理数据:修改上面的html代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <!-- 导入axios --> <script src="https://unpkg.com/axioshttps://img.qb5200.com/download-x/dist/axios.min.js"></script> <!-- 导入qs --> <script src="https://cdn.bootcss.com/qs/6.5.2/qs.min.js"></script> </head> <body> <!-- POST 请求 --> <form method="post"> <p>用户名:<input id="username" type="text" name="username" value="admin"> </p> <br /> <p>密 码:<input id="password" type="text" name="password" value="123456"> </p> <br /> <p><input id="btn" type="submit" value="登录" /></p> </form> </body> <script> document.getElementById("btn").onclick = function () { //获取用户输入的登录信息 let username = document.getElementById('username').value; let password = document.getElementById('password').value; // 用qs处理数据对象 //qs的原理:就是将对象转变成字符串拼接到url上再发post请求 let data = Qs.stringify({ username: username, password: password }); console.log(data);//username=admin&password=123456 //阻止submit默认行为:表单提交刷新页面 event.preventDefault(); //提交请求获取响应数据 axios.post("http://www.test.comhttps://img.qb5200.com/download-x/day05/jiekou.php", data).then(res => { console.log(res); }).catch(err => { console.log(err); }) } </script> </html>
方法Ⅱ.后端开放options请求跨域,并用对应的方法获取options提交的复杂数据
<?php // 制定允许其他域名访问 header("Access-Control-Allow-Origin:*"); // 响应类型 header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH'); // 响应头设置 header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization"); //如果是options请求,就结束执行下面语句 if($_SERVER['REQUEST_METHOD']=='OPTIONS'){ //exit是用来结束程序执行的,如果参数是字符串,PHP将会直接把字符串输出, //如果参数是整型(范围是0-254),那个参数将会被作为结束状态使用。 exit('options类型的请求,结束'); } //option请求无法用常规方法($_GET, $_POST, $_REQUEST)获取请求参数 $option_data_str = file_get_contents("php://input"); $option_data = json_decode($option_data_str,true); $username = isset($option_data['username'])?$option_data['username']:""; $password = isset($option_data['password'])?$option_data['password']:""; // 判断form表单中key if(isset($username) && isset($password)){ // 判断username和password if($username == "admin" && $password == "123456"){ $result = array("success" => 1, "code" => 101, "data" => array("username" => $username, "password" => $password)); }else{ $result = array("success" => 0, "code" => 103, "data" => null); } }else{ $result = array("success" => 0, "code" => 100, "data" => null); } // 将错误信息(数组)转换成json类型,返回前端 echo(json_encode($result)); ?>
小结::
Ⅰ.个人是比较倾向于由后端来解决(前端还要引入qs插件,没什么必要)
Ⅱ.在vue里面使用qs的步骤
➀qs是一个npm仓库所管理的包,可通过npm install qs命令进行安装.
传送门[https://www.npmjs.com/package/qs](https://www.npmjs.com/package/qs)
qs.parse()将URL解析成对象的形式
qs.stringify()将对象 序列化成URL的形式,以&进行拼接(我们大都用到这个)
➁在全局main.js里引入qs并配置方法到原型上
import qs from 'qs'; Vue.prototype.$qs = qs;
在所有的vue实例组件里都可以直接用this.$qs.stringify(要处理的数据),进行数据转换
加载全部内容