2017-08-15 76 views
0

我正在使用vue.js來編寫應用程序,並且我嘲笑dev-server.js中的localhost的登錄api,現在我想將有關登錄api的代碼分離爲獨立的文件,我該怎麼做?此外,還有一些關於CORS一些代碼,這裏是代碼:如何將vue中的dev-server.js文件拆分爲幾個分離的文件?

var app = express() 
var bodyParser = require('body-parser') 
var multer = require('multer') 
var upload = multer() 

app.use(bodyParser.json()) 
app.use(bodyParser.urlencoded({extended: true})) 
// CORS 
var allowCrossDomain = function (req, res, next) { 
    res.header('Access-Control-Allow-Origin', 'http://localhost:8080') 
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE') 
    res.header('Access-Control-Allow-Headers', 'Content-Type, X-Token') 
    res.header('Access-Control-Allow-Credentials', 'true') 
    next() 
} 
app.use(allowCrossDomain) 



// mock localhost api 
var apiRoutes = express.Router() 
// login api; 
const userAccountList = ['100000', '100001', '100002', '100003'] 
apiRoutes.post('/user/login', upload.array(), function (req, res) { 
    if (userAccountList.indexOf(req.body.account) < 0){ 
    return res.json({ 
     code: 50000, 
     msg: 'the account or the password is not correct, please try again' 
    }); 
    } 
} 
app.use('/api', apiRoutes); 

回答

0

(我認爲這是一個有關節點問題和表達,而不是vue.js)

雖然表達的是基本建成與中間件的Web應用程序,我認爲這是一次你的邏輯分割成不同的中間件。

所以,你可以把你的登錄邏輯到一個獨立的.js文件像中間件:

// login.js 

const userAccountList = ['100000', '100001', '100002', '100003'] 

const loginMiddleware = function (req, res, next) { 
    if (userAccountList.indexOf(req.body.account) < 0){ 
    res.json({ 
     code: 50000, 
     msg: 'the account or the password is not correct, please try again' 
    }); 
    } 
}; 

module.exports = loginMiddleware; 

然後從你的應用程序要求它像:

// app.js 

const loginMiddleware = require('./login'); 

// ... 

apiRoutes.post('/user/login', loginMiddleware); 

下面是官方文件明確關於如何正確編寫你的中間件:https://expressjs.com/en/guide/using-middleware.html

+0

順便說一句,有一個CORS官方中間件:https://github.com/expressjs/cors。所以你不需要自己寫。 –

0

也許檢出一個模塊捆綁像webpack。它允許您將代碼拆分成可以加載在一起的不同捆綁包。