在開發環境的時候我們是要處理跨域這個問題的。
如果我們在開發環境要進行跨域處理想要一勞永逸該怎麼辦呢?
本文介紹的是thinkjs解決跨域的方法。有倆種方法,第二種是最省事的。
第一種方法:寫一個父類方法進行繼承使用。
如果在不引入任何依賴的情況下我們可以這麼做:
在你的src/controller/base.js裏面追加一個方法專門處理跨域的:
module.exports = class extends think.Controller {
__before() {
}
setCorsHeader() {
this.header('Access-Control-Allow-Origin', this.header('origin') || '*');
this.header('Access-Control-Allow-Headers', 'x-requested-with');
this.header('Access-Control-Request-Method', 'GET,POST,PUT,DELETE,OPTIONS');
this.header('Access-Control-Allow-Credentials', 'true');
}
}
然後你的每個自己的controller都繼承這個base.js再調用他的setCorsHeader方法那麼就可以實現共用了。
文件目錄:src/controller/user.js
const Base = require('./base');
module.exports = class extends Base {
// 獲取用戶列表
async queryUsersAction() {
this.setCorsHeader(); // 調用從base.js繼承來的方法
const user = this.ctx.model('user');
const res = await user.getList();
return this.success(res);
}
};
第二種方法:安裝依賴進行使用
1.安裝 kcors 包。
$ npm install kcors -S
2.使用中間件
/src/config/middleware.js
const path = require('path');
const isDev = think.env === 'development';
const kcors = require('kcors');
module.exports = [
{
handle: 'trace', // trace 中間件最好放在最前面,否則在 trace 之前的錯誤沒辦法 catch 到。
enable: !think.isCli,
options: {
debug: isDev
}
},
{
handle: kcors, // 全局處理跨域,所有請求都會允許跨域,如果想要進行相關配置請看kcors文檔進行配置
options: {
origin: '*',
credentials: true,
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'
}
},
{
handle: 'meta',
options: {
logRequest: isDev,
sendResponseTime: isDev
}
},
{
handle: 'resource',
enable: isDev,
options: {
root: path.join(think.ROOT_PATH, 'www'),
publicPath: /^\/(static|favicon\.ico)/
}
},
{
handle: 'payload',
options: {}
},
{
handle: 'router',
options: {}
},
'logic',
'controller'
];
如果所有的請求都允許跨域的話第二種方法是最省事的~可以直接使用。如果要進行部分限制那就使用第一種,稍微麻煩點!
如果本文幫助到您了歡迎給個三連。哈哈哈【吳小迪在線求三連】