2016-06-03 2 views
1

В настоящее время я пишу веб-приложение со стеком MEAN и тестирую, работает ли мой сервер nodejs. Вот мой server.js:Неожиданный токен. при запуске server.js

// server.js 
    'use strict'; 

    // modules ================================================= 
    const path = require('path'); 
    const express = require('express'); 
    const app = express(); 
    const bodyParser = require('body-parser'); 
    const methodOverride = require('method-override'); 

    // configuration =========================================== 

    // config files 
    const db = require('./config/db'); 

    // set our port 
    var port = process.env.PORT || 8080; 

    // connect to mongoDB 
    // (uncomment after entering in credentials in config file) 
    // mongoose.connect(db.url); 

    // get all data/stuff of the body (POST) parameters 
    // parse application/json 
    app.use(bodyParser.json()); 

    // parse application/vnd.api+json as json 
    app.use(bodyParser.json({ type: 'application/vnd.api+json' })); 

    // parse application/x-www-form-urlencoded 
    app.use(bodyParser.urlencoded({ extended: true })); 

    // override with the X-HTTP-Method-Override header in the request simulate DELETE/PUT 
    app.use(methodOverride('X-HTTP-Method-Override')); 

    // set the static files location /public/img will be /img for users 
    app.use(express.static(__dirname + '/public')); 

    // routes ================================================== 
    require('./app/routes')(app); // configure our routes 

    // start app =============================================== 
    // startup our app at http://localhost:8080 
    app.listen(port); 

    // shoutout to the user 
    console.log('App running on port ' + port); 

    // expose app 
    exports = module.exports = app; 

я в настоящее время он перенаправляет все маршруты в мой файл index.html, чтобы проверить, чтобы убедиться, что мои взгляды работают. Вот мой routes.js:

// models/routes.js 

    // grab the user model 
    var User = require('./models/user.js'); 

    module.exports = { 
     // TODO: Add all routes needed by application 

     // frontend routes ========================================================= 
     // route to handle all angular requests 
     app.get('*', function(req, res) { 
      res.sendfile('./public/index.html'); // load our public/index.html file 
     }); 
    }; 

Однако, когда я пытаюсь запустить node server.js, это дает мне эту ошибку:

/home/hess/Projects/FitTrak/app/routes.js 
     app.get('*', function(req, res) { 
     ^

    SyntaxError: Unexpected token . 

Кто-нибудь есть какие-либо идеи, что причина этого? Я проверил, и все мои скобки и скобки закрыты и написаны правильно.

+3

Вы строите плоский объект буквально. module.exports = {ключ: 'значение'} - это хорошо. –

+3

Я предполагаю, что вы можете сделать что-то вроде: module.exports = function (app) {/ * ваш код * /} –

+1

Мы не делаем РЕШЕНИЯ в названии здесь. Если вы ответили на свой вопрос, отправьте ответ и отметьте его как принятый или удалите вопрос. – j08691

ответ

1

Как Jose Hermosilla Rodrigo в своем комментарии, вы объявляете объект literal module.exports неправильным. Он должен выглядеть следующим образом, вместо:

module.exports = function(app) { 
    app.get('*', function(req, res) { 
     res.sendfile('./public/index.html'); // load our public/index.html file 
    }); 
}; 
1

просто попробуйте этот код ...

// Модели/routes.js

var express=require('express'); 
var app=express(); 

// TODO: Add all routes needed by application 

     // frontend routes ========================================================= 
     // route to handle all angular requests 
app.get('*', function(req, res) { 
      res.sendfile('./public/index.html'); 
     }); 

module.exports = route; 

server.js

'use strict'; 

const path = require('path'); 
const express = require('express'); 
const app = express(); 
const bodyParser = require('body-parser'); 
var route=require('./models/route.js'); 
const methodOverride = require('method-override'); 

// configuration =========================================== 

// config files 
const db = require('./config/db'); 

// set our port 
var port = process.env.PORT || 8080; 

// connect to mongoDB 
// (uncomment after entering in credentials in config file) 
// mongoose.connect(db.url); 

// get all data/stuff of the body (POST) parameters 
// parse application/json 
app.use(bodyParser.json()); 

// parse application/vnd.api+json as json 
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); 

// parse application/x-www-form-urlencoded 
app.use(bodyParser.urlencoded({ extended: true })); 

// override with the X-HTTP-Method-Override header in the request simulate DELETE/PUT 
app.use(methodOverride('X-HTTP-Method-Override')); 

// set the static files location /public/img will be /img for users 
app.use(express.static(__dirname + '/public')); 

// routes ================================================== 
require('./app/routes')(app); // configure our routes 

// start app =============================================== 
// startup our app at http://localhost:8080 
app.listen(port); 

// shoutout to the user 
console.log('App running on port ' + port); 


app.use('/',route); 
0

Если вы используете стек MEAN. Я бы предложил вам использовать собственное промежуточное программное обеспечение маршрутизатора для обработки всех ваших маршрутов. Просто включите.

var router = express.Router(); 
    //use router to handle all your request 
    router.get(/xxx,function(req, res){ 
    res.send(/xxxx); 
    }) 

    // You may have n number of router for all your request 
    //And at last all you have to do is export router 

    module.exports = router; 
Смежные вопросы