thinkjs 跨域處理:
async __before(){
this.header("Access-Control-Allow-Origin",this.header("origin")||"*");
this.header("Access-Control-Allow-Headers", "x-requested-with,content-type");
this.header("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
this.header('Access-Control-Allow-Credentials',true);
let method=this.method.toLowerCase();
// 處理預檢請求,給body設置一個值,不然報錯404;
if(method==="options"){
this.ctx.body=200;
return false;
}
}
複製代碼
代碼示例:
const BaseRest = require('../rest.js');
module.exports = class extends BaseRest {
async __before(){
this.header("Access-Control-Allow-Origin",this.header("origin")||"*");
this.header("Access-Control-Allow-Headers", "x-requested-with,content-type");
this.header("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
this.header('Access-Control-Allow-Credentials',true);
let method=this.method.toLowerCase();
// 處理預檢請求,給body設置一個值,不然報錯404;
if(method==="options"){
this.ctx.body=200;
return false;
}
}
async loginAction() {
let {email, password,type} = this.post();
const salt = 'geekQiaQia';
password = think.md5(salt + password);
const login_ip = this.ctx.ip;
let dateTime = new Date();
let login_time = think.datetime(dateTime);
try{
let user=await this.model("user").where({email: email}).find();
if(user.password&&user.password===password){
let logStatus= await this.model("log").where({email}).find();
console.log("email is exist=",logStatus.email);
if(logStatus.email){
// 若是登陸成功,則update登陸日誌;
await this.model("log").where({email}).update({
flag:1,login_time,password:password,login_ip
});
}else{
// 若是首次登陸,則添加首次登陸記錄;
await this.model("log").add({
flag:1,email,login_time,password:password,login_ip
});
}
let resJsonObj={
status:"true",
code:"0000",
desc:"操做成功",
type,
currentAuthority:"user",
};
return this.success(resJsonObj);
}else{
return this.fail("用戶名或者密碼錯誤");
}
}catch (e) {
think.logger.error(new Error(e));
let resJsonObj={
status:"false",
code:"0110",
desc:"系統內部錯誤"
};
return this.fail(resJsonObj, e);
}
}
};
複製代碼