HackHands Satellizer示例 - 意外令牌问题

时间:2015-07-22 10:41:39

标签: javascript angularjs node.js express

我正在使用这个HackHands示例开始使用Satellizer并坚持运行快速服务器 - https://hackhands.com/building-instagram-clone-angularjs-satellizer-nodejs-mongodb/

这是我的Server.js -

var bcrypt = require('bcryptjs');
var bodyParser = require('body-parser');
var cors = require('cors');
var express = require('express');
var jwt = require('jwt-simple');
var moment = require('moment');
var mongoose = require('mongoose');
var path = require('path');
var request = require('request');

var config = require('./config');

var User = mongoose.model('User', new mongoose.Schema({

   instagramId: { type: String, index: true },
   email: { type: String, unique: true, lowercase: true },
   password: { type: String, select: false },
   username: String,
   fullname: String,
   picture: String,
  accesstoken: String
 }));
mongoose.connect(config.db);

var app = express();

app.set('port', process.env.PORT || 3000);
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

function createToken(user){
  var payload = {
   exp: moment().add(14, 'days').unix(),
    iat: moment().unix(),
    sub: user._id
  };
  return jwt.encode(payload, config.tokenSecret);
}


function isAuthenticated(req, res, next) {
  if (!(req.headers && req.headers.authorization)) {
return res.status(400).send({ message: 'You did not provide a JSON Web Token in the Authorization header.' });
  }

  var header = req.headers.authorization.split(' ');
  var token = header[1];
  var payload = jwt.decode(token, config.tokenSecret);
  var now = moment().unix();

  if (now > payload.exp) {
    return res.status(401).send({ message: 'Token has expired.' });
  }

  User.findById(payload.sub, function(err, user) {
    if (!user) {
      return res.status(400).send({ message: 'User no longer exists.' });
    }

   req.user = user;
    next();
  })
}


app.post('/auth/login', function(req, res) {
  User.findOne({ email: req.body.email }, '+password', function(err, user) {
if (!user) {
  return res.status(401).send({ message: { email: 'Incorrect email' } });
}

bcrypt.compare(req.body.password, user.password, function(err, isMatch) {
  if (!isMatch) {
    return res.status(401).send({ message: { password: 'Incorrect password' } });
  }

  user = user.toObject();
  delete user.password;

  var token = createToken(user);
  res.send({ token: token, user: user });
});
  });
});

app.post('/auth/signup', function(req, res) {
  User.findOne({ email: req.body.email }, function(err, existingUser) {
if (existingUser) {
  return res.status(409).send({ message: 'Email is already taken.' });
}

var user = new User({
  email: req.body.email,
  password: req.body.password
});

bcrypt.genSalt(10, function(err, salt) {
  bcrypt.hash(user.password, salt, function(err, hash) {
    user.password = hash;

    user.save(function() {
      var token = createToken(user);
      res.send({ token: token, user: user });
    });
  });
});
  });
});

app.post('/auth/instagram', function(req, res) {
  var accessTokenUrl = 'https://api.instagram.com/oauth/access_token';

  var params = {
client_id: req.body.clientId,
redirect_uri: req.body.redirectUri,
client_secret: config.clientSecret,
code: req.body.code,
grant_type: 'authorization_code'
  };

  // Step 1\. Exchange authorization code for access token.
  request.post({ url: accessTokenUrl, form: params, json: true }, function(error, response, body) {

// Step 2a. Link user accounts.
if (req.headers.authorization) {

  User.findOne({ instagramId: body.user.id }, function(err, existingUser) {

    var token = req.headers.authorization.split(' ')[1];
    var payload = jwt.decode(token, config.tokenSecret);

    User.findById(payload.sub, '+password', function(err, localUser) {
      if (!localUser) {
        return res.status(400).send({ message: 'User not found.' });
      }

      // Merge two accounts.
      if (existingUser) {

        existingUser.email = localUser.email;
        existingUser.password = localUser.password;

        localUser.remove();

        existingUser.save(function() {
          var token = createToken(existingUser);
          return res.send({ token: token, user: existingUser });
        });

      } else {
        // Link current email account with the Instagram profile information.
        localUser.instagramId = body.user.id;
        localUser.username = body.user.username;
        localUser.fullName = body.user.full_name;
        localUser.picture = body.user.profile_picture;
        localUser.accessToken = body.access_token;

        localUser.save(function() {
          var token = createToken(localUser);
          res.send({ token: token, user: localUser });
        });

      }
    });
  });
} else {
  // Step 2b. Create a new user account or return an existing one.
  User.findOne({ instagramId: body.user.id }, function(err, existingUser) {
    if (existingUser) {
      var token = createToken(existingUser);
      return res.send({ token: token, user: existingUser });
    }

    var user = new User({
      instagramId: body.user.id,
      username: body.user.username,
      fullName: body.user.full_name,
      picture: body.user.profile_picture,
      accessToken: body.access_token
    });

    user.save(function() {
      var token = createToken(user);
      res.send({ token: token, user: user });
    });
  });
}
  });
});

     app.get('/api/feed', isAuthenticated, function(req, res) {
  var feedUrl = 'https://api.instagram.com/v1/users/self/feed';
  var params = { access_token: req.user.accessToken };

  request.get({ url: feedUrl, qs: params, json: true }, function(error, response, body) {
if (!error && response.statusCode == 200) {
  res.send(body.data);
}
  });
});

app.get('/api/media/:id', isAuthenticated, function(req, res, next) {
  var mediaUrl = 'https://api.instagram.com/v1/media/' + req.params.id;
  var params = { access_token: req.user.accessToken };

  request.get({ url: mediaUrl, qs: params, json: true }, function(error, response, body) {
if (!error && response.statusCode == 200) {
  res.send(body.data);
}
  });
 });

app.post('/api/like', isAuthenticated, function(req, res, next) {
  var mediaId = req.body.mediaId;
  var accessToken = { access_token: req.user.accessToken };
  var likeUrl = 'https://api.instagram.com/v1/media/' + mediaId + '/likes';

  request.post({ url: likeUrl, form: accessToken, json: true }, function(error, response, body) {
if (response.statusCode !== 200) {
  return res.status(response.statusCode).send({
    code: response.statusCode,
    message: body.meta.error_message
  });
}
res.status(200).end();
  });
});


app.listen(app.get('port'), function() {
  console.log('Express server listening on port ' + app.get('port'));
    });

这是我运行npm start cmd时的错误日志 -

1 verbose cli [ 'node', '/usr/local/bin/npm', 'start' ]

2 info使用npm@2.7.5

3 info使用node@v0.12.2

4详细节点符号链接/ usr / local / bin / node

5详细的run-script ['prestart','start','poststart']

6 info prestart instagram-server@0.0.0

7 info start instagram-server@0.0.0

8生命周期中的详细不安全 - 永久性

9 info instagram-server@0.0.0执行启动脚本失败

10详细堆栈错误:instagram-server@0.0.0 start:node server.js

10详细堆栈退出状态1

EventEmitter上的10个详细堆栈。

(在/ usr /本地/ LIB / node_modules / NPM / LIB / utils的/ lifecycle.js:213:16) EventEmitter.emit上的10个详细堆栈(events.js:110:17)

ChildProcess上的10个详细堆栈。

(在/ usr /本地/ LIB / node_modules / NPM / LIB / utils的/ spawn.js:14:12)

ChildProcess.emit上的10个详细堆栈(events.js:110:17)

10 verbose stack     at maybeClose (child_process.js:1015:16)

10 verbose stack     at Process.ChildProcess._handle.onexit (child_process.js:1087:5)

11 verbose pkgid instagram-server@0.0.0

12 verbose cwd /Users/nshrivastava/Desktop/instagram/server

13 error Darwin 14.3.0

14 error argv "node" "/usr/local/bin/npm" "start"

15 error node v0.12.2

16 error npm  v2.7.5

17 error code ELIFECYCLE

18 error instagram-server@0.0.0 start: `node server.js`

18 error Exit status 1

19 error Failed at the instagram-server@0.0.0 start script 'node server.js'.

19 error This is most likely a problem with the instagram-server package,

19 error not with npm itself.

19 error Tell the author that this fails on your system:

19 error     node server.js

19 error You can get their info via:

19 error     npm owner ls instagram-server


19 error There is likely additional logging output above.

20 verbose exit [ 1, true ]

我总是在终端上收到此错误 - SyntaxError:意外的令牌;     在exports.runInThisContext(vm.js:73:16)     在Module._compile(module.js:443:25)     在Object.Module._extensions..js(module.js:478:10)     在Module.load(module.js:355:32)     在Function.Module._load(module.js:310:12)     在Function.Module.runMain(module.js:501:10)     在启动时(node.js:129:16)     在node.js:814:3

不确定我在这里缺少什么。有人可以帮忙吗?

我的package.json粘贴在下面 -

{

“name”:“instagram-server”,   “版本”:“0.0.0”,   “脚本”:{     “start”:“node server.js”   },   “依赖”:{     “bcryptjs”:“^ 2.0.2”,     “body-parser”:“^ 1.8.1”,     “cors”:“^ 2.4.2”,     “表达”:“^ 4.9.0”,     “jwt-simple”:“^ 0.2.0”,     “时刻”:“^ 2.8.3”,     “猫鼬”:“^ 3.8.17”,     “请求”:“^ 2.44.0”   }

}

1 个答案:

答案 0 :(得分:1)

在遵循本教程的同时运行快速服务器时遇到了同样的问题。我所做的就是删除了&

更改

if (!(req.headers && req.headers.authorization))

if (!(req.headers && req.headers.authorization))

您还需要为其中包含&的所有后续功能更改它。