gpt4 book ai didi

javascript - HackHands Satellizer 示例 - 意外的 token 问题

转载 作者:行者123 更新时间:2023-12-03 09:29:30 25 4
gpt4 key购买 nike

我正在使用这个 HackHands 示例来开始使用 Satellizer 并坚持运行 Express 服务器 - 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 使用 npm@2.7.5 的信息

3 使用node@v0.12.2的信息

4 详细 Node 符号链接(symbolic link)/usr/local/bin/node

5 个详细运行脚本 [ 'prestart', 'start', 'poststart' ]

6 信息预启动 instagram-server@0.0.0

7 信息启动 instagram-server@0.0.0

生命周期 true 中的 8 个详细不安全权限

9 info instagram-server@0.0.0 无法执行启动脚本

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

10 详细堆栈退出状态 1

EventEmitter 上有 10 个详细堆栈。

(/usr/local/lib/node_modules/npm/lib/utils/lifecycle.js:213:16)EventEmitter.emit 处的 10 个详细堆栈 (events.js:110:17)

ChildProcess 中的 10 个详细堆栈。

(/usr/local/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 ]

我总是在终端上收到此错误 -语法错误:意外的标记; 在 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粘贴在下面-

{

“名称”:“instagram 服务器”, “版本”:“0.0.0”, “脚本”:{ “开始”:“Node 服务器.js” }, “依赖项”:{ "bcryptjs": "^2.0.2", "body-parser": "^1.8.1", “cors”:“^2.4.2”, " express ": "^4.9.0", "jwt-simple": "^0.2.0", "时刻": "^2.8.3", " Mongoose ": "^3.8.17", “请求”:“^2.44.0” }

}

最佳答案

我在按照本教程运行 Express 服务器时遇到了同样的问题。我所做的只是删除了 &

改变

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

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

您还需要为所有包含 & 的后续函数更改它。

关于javascript - HackHands Satellizer 示例 - 意外的 token 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31560799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com