2017-08-15 17 views
0

私はvue.jsを使ってアプリケーションを作成していますが、dev-server.jsにlocalhostのログインapiを偽装しました。これでlogin apiのコードを独立したファイルに分割したいのですが、どうすればいいですか?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の)

Expressはミドルウェアと基本的に構築されたWebアプリケーションですが、私はそれが別のミドルウェアにあなたのロジックを分割するための時間だと思います。その後のようなあなたのアプリから、それを必要とする

// 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); 

は公式速達文書である

だから、のようなミドルウェアとして独立した.jsファイルにログインロジックを置くことができますhttps://expressjs.com/en/guide/using-middleware.html

+0

ところで、CORSの公式ミドルウェアはhttps://github.com/expressjs/corsです。だから、自分で書く必要はありません。 –

0

たぶんwebpackのようなモジュールバンドラをチェックアウト:CORSに関するいくつかのコードがあるだけでなく、ここにコードがあります。それはコードを一緒にロードできる異なるバンドルに分割することを可能にします。

関連する問題