-
#1 laravel直接在routes里面的match里面添加即可,如下:
Route::match(['get', 'post', 'options'], '/get_app_token', 'App\UserLogin@get_app_token')
-
#2 如下定义修改一个基于ES语法的Fetch方法,将method定义为options,就构建了一个OPTIONS请求:
可见一个option会发送2次请求,第一次为options,第二次也为options(别人的是post请求)。
在拼接body参数时,发现,将参数拼接在url当中服务端才能接收到参数;而将参数拼接在body里面服务端是接收不到参数的。
options第二次请求看上去是post请求,但是服务端却接收不到参数,很蛋疼。
-
封装的fetch请求:
"request_options": function (api, map_data, call_func) { // options会产生两次请求
let request = {};
let request_text = "";
let test_data = [api, map_data, call_func];
// 开始-Fetch-请求数据
// const post_api = config.api_url + "admin/login_check";
// const map_body = new Map([ // 要提交数据
// ["login_token", login_token],
// ]);
let map = map_data;
let body = "";
for (let [k, v] of map) { body += k+"="+v+"&"; } // 拼装数据,限制2MB最佳
// let post_api = api;
let tag = "&";
if (api.indexOf("?") === -1){
tag = "?";
}
let post_api = api + tag + body;
fetch(post_api, {
method: "options", // get/post/options
mode: "cors", // same-origin/no-cors/cors
cache: "no-cache",
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
},
body: body, // 格式要求:body:"key1=val1&key2=val2";get方法不需要body
}).then(function (response){
if (response.status === 200){return response;}
}).then(function (data) {
return data.text();
}).then(function(text){
// 统一格式转换
let back = null;
let res = null;
if (typeof text === "string"){
back = text;
try {
res = JSON.parse(text);
}catch (e) {
res = text;
}
}else if (typeof text === "object"){
back = JSON.stringify(text);
res = text;
}else {console.log("Unknown Typeof = " + typeof text); back = text;}
view.log("①Typeof:\n" + typeof text + "\n②Api_data:\n" + back);
request = {
"request_status": true,
"request_back": res,
"request_text": back,
};
request_text = back;
call_func(request, test_data, request_text);
}).catch(function(error){
let error_info = "▲ Fetch遇到错误:" + error +" ▲";
console.log("%c"+error_info, "color:red;font-weight:bold;font-size:18px;");
request = {
"request_status": false,
"request_back": "",
};
request_text = error_info;
call_func(request, test_data, error_info);
});
// 结束-Fetch
},
-
测试接口:
function run_req(request, test_data, text) {
view.log([request, test_data, text]);
}
function test_req() {
console.log("===1===");
let map = new Map([
["app_class", "pc"],
["url", "20191205"],
]);
view.request_options("http://47.111.168.64/cswd/public/index.php/api/app/get_app_token", map, run_req);
}
test_req()
-
-