Boa tarde
Senhores, Estou estudando o livro porem estou com um erro no primeiro exercício no capitulo 04;
Meu ambiente:
SO: (Linux not3130 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt20-1+deb8u3 (2016-01-17) x86_64 GNU/Linux)
NODE: (v5.4.1)
NPM:(3.3.12)
de acordo com as instruções do capitulo meu arquivo package.json
{
“name”: “ntask-api”,
“version”: “1.0.0”,
“description”: “API de gestão de tarefas”,
“main”: “index.js”,
“scripts”: {
“start”: “babel-node index.js”
},
“author”: “Caio Ribeiro Pereira”,
“dependencies”: {
“babel”: “^6.3.26”,
“express”: “^4.13.4”
}
}
Criei o arquivo “index.js” com o seguinte conteúdo:
import express from “express”;
const PORT = 3000;
const app = express();
app.get(“/”, (req,res) => res.json({status: “NTask API”}));
app.listen(PORT, () => console.log(‘NTask API - porta ${PORT}’));
Problema:
ao rodar o comando “npm start”, é apresentado o seguinte erro:
ntask-api$ npm start
ntask-api@1.0.0 start /home/leonardo/Programas/Angular/LIVRO_NODE/ntask-api
babel-node index.js
The CLI has been moved into the package babel-cli
. See @babel/cli · Babel
npm ERR! Linux 3.16.0-4-amd64
npm ERR! argv “/usr/local/bin/node” “/usr/local/bin/npm” “start”
npm ERR! node v5.4.1
npm ERR! npm v3.3.12
npm ERR! code ELIFECYCLE
npm ERR! ntask-api@1.0.0 start: babel-node index.js
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ntask-api@1.0.0 start script ‘babel-node index.js’.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the ntask-api package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! babel-node index.js
npm ERR! You can get their info via:
npm ERR! npm owner ls ntask-api
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! /home/leonardo/Programas/Angular/LIVRO_NODE/ntask-api/npm-debug.log
Conteúdo do arquivo npm-debug.log:
0 info it worked if it ends with ok
1 verbose cli [ ‘/usr/local/bin/node’, ‘/usr/local/bin/npm’, ‘start’ ]
2 info using npm@3.3.12
3 info using node@v5.4.1
4 verbose run-script [ ‘prestart’, ‘start’, ‘poststart’ ]
5 info lifecycle ntask-api@1.0.0~prestart: ntask-api@1.0.0
6 silly lifecycle ntask-api@1.0.0~prestart: no script for prestart, continuing
7 info lifecycle ntask-api@1.0.0~start: ntask-api@1.0.0
8 verbose lifecycle ntask-api@1.0.0~start: unsafe-perm in lifecycle true
9 verbose lifecycle ntask-api@1.0.0~start: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bin:/home/leonardo/Programas/Angular/LIVRO_NODE/ntask-api/node_modules/.bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin:/home/leonardo/Programas/Angular/Android/android-sdk-linux/platform-tools:/home/leonardo/Programas/Angular/Android/android-sdk-linux/tools
10 verbose lifecycle ntask-api@1.0.0~start: CWD: /home/leonardo/Programas/Angular/LIVRO_NODE/ntask-api
11 silly lifecycle ntask-api@1.0.0~start: Args: [ ‘-c’, ‘babel-node index.js’ ]
12 silly lifecycle ntask-api@1.0.0~start: Returned: code: 1 signal: null
13 info lifecycle ntask-api@1.0.0~start: Failed to exec start script
14 verbose stack Error: ntask-api@1.0.0 start: babel-node index.js
14 verbose stack Exit status 1
14 verbose stack at EventEmitter. (/usr/local/lib/node_modules/npm/lib/utils/lifecycle.js:232:16)
14 verbose stack at emitTwo (events.js:87:13)
14 verbose stack at EventEmitter.emit (events.js:172:7)
14 verbose stack at ChildProcess. (/usr/local/lib/node_modules/npm/lib/utils/spawn.js:24:14)
14 verbose stack at emitTwo (events.js:87:13)
14 verbose stack at ChildProcess.emit (events.js:172:7)
14 verbose stack at maybeClose (internal/child_process.js:821:16)
14 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)
15 verbose pkgid ntask-api@1.0.0
16 verbose cwd /home/leonardo/Programas/Angular/LIVRO_NODE/ntask-api
17 error Linux 3.16.0-4-amd64
18 error argv “/usr/local/bin/node” “/usr/local/bin/npm” “start”
19 error node v5.4.1
20 error npm v3.3.12
21 error code ELIFECYCLE
22 error ntask-api@1.0.0 start: babel-node index.js
22 error Exit status 1
23 error Failed at the ntask-api@1.0.0 start script ‘babel-node index.js’.
23 error Make sure you have the latest version of node.js and npm installed.
23 error If you do, this is most likely a problem with the ntask-api package,
23 error not with npm itself.
23 error Tell the author that this fails on your system:
23 error babel-node index.js
23 error You can get their info via:
23 error npm owner ls ntask-api
23 error There is likely additional logging output above.
24 verbose exit [ 1, true ]
Update 01
Utilizei os comando:
ntask-api$ npm install babel-core --save
ntask-api$ npm install babel-cli -g
E agora ao executar o npm start apresenta o seguinte erro:
ntask-api$ npm start
ntask-api@1.0.0 start /home/leonardo/Programas/Angular/LIVRO_NODE/ntask-api
babel-node index.js
/home/leonardo/Programas/Angular/LIVRO_NODE/ntask-api/index.js:1
(function (exports, require, module, __filename, __dirname) { import express from “express”;
^^^^^^
SyntaxError: Unexpected token import
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at loader (/usr/local/lib/node_modules/babel-cli/node_modules/babel-register/lib/node.js:130:5)
at Object.require.extensions.(anonymous function) [as .js] (/usr/local/lib/node_modules/babel-cli/node_modules/babel-register/lib/node.js:140:7)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:429:10)
at /usr/local/lib/node_modules/babel-cli/lib/_babel-node.js:161:27
at Object. (/usr/local/lib/node_modules/babel-cli/lib/_babel-node.js:162:7)
at Module._compile (module.js:397:26)
npm ERR! Linux 3.16.0-4-amd64
npm ERR! argv “/usr/local/bin/node” “/usr/local/bin/npm” “start”
npm ERR! node v5.4.1
npm ERR! npm v3.3.12
npm ERR! code ELIFECYCLE
npm ERR! ntask-api@1.0.0 start: babel-node index.js
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ntask-api@1.0.0 start script ‘babel-node index.js’.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the ntask-api package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! babel-node index.js
npm ERR! You can get their info via:
npm ERR! npm owner ls ntask-api
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! /home/leonardo/Programas/Angular/LIVRO_NODE/ntask-api/npm-debug.log
No site (Babel)
Explica uma forma utilizando presets no arquivo .babelrc.
Update 02
Utilizando os comando:
ntask-api$ npm install --save-dev babel-core
ntask-api$ npm install babel-preset-es2015 --save-dev
Criando o arquivo .babelrc
echo ‘{ “presets”: [“es2015”] }’ > .babelrc
agora ao executar o npm start recebo a seguinte saida:
ntask-api$ npm start
ntask-api@1.0.0 start /home/leonardo/Programas/Angular/LIVRO_NODE/ntask-api
babel-node index.js
NTask API - porta ${PORT}
reparem no ${PORT}, não exibiu o valor da constante 3000, mas ao acessar (127.0.0.1:3000) segue a saida
{“status”:“NTask API”}, que seria a saída correta.
Update 03
O problema de não exibir a constante resolvido, sintaxe errada (') o correto é (`)
Teoricamente esta tudo funcionando conforme o indicado no livro, apenas diferente a respeito da instalação do babel, a pergunta é o que fiz até agora esta certo?
Update 4 - Capitulo 6.8 na pagina 62
Existe a instrução:
import bodyParser from “body-parser”;
module.exports = app => {
app.set(“port”, 3000);
app.set(“json spaces”, 4);
app.use(bodyParser.json());
app.use((req, res, next) => {
delete req.body.id;
next();
});
};
Porem anteriormente não menciona nada sobre a instalação:
ntask-api$ npm install body-parser --save
Update 5 - Capitulo 8.2 na pagina 88
Temos a instrução:
libs/boot.js para que não seja iniciada quando
process.env.NODE_ENV estiver com valor “test” .
mos modificar o
Para alterar isso, edite o libs/boot.js com esse código:
module.exports = app => {
if (process.env.NODE_ENV !== “test”) {
app.db.sequelize.sync().done(() => {
app.listen(app.get(“port”), () => {
console.log(NTask API - porta ${app.get("port")}
);
});
});
}
}
Porem ao inicializarmos a aplicação em ambiente de teste (npm test), não executa o trecho
" app.db.sequelize.sync().done(() " o na primeira vez não cria a base de teste. resolvi utilizando o codigo:
module.exports = app => {
if (process.env.NODE_ENV !== "test") {
app.db.sequelize.sync().done(() => {
app.listen(app.get("port"), () => {
console.log(`NTask API - porta ${app.get("port")}`);
});
});
} else {
app.db.sequelize.sync().done(() => {
});
};
};
Update 6 - Capitulo 5.3 na paginas 47 e 48
Neste capitulo criamos o model do usuário Users: utilizando o seguinte codigo:
Crie o arquivo
models/users.js com as seguintes definições:
module.exports = (sequelize, DataType) => {
const Users = sequelize.define(“Users”, {
id: {
type: DataType.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataType.STRING,
allowNull: false,
validate: {
notEmpty: true
}
},
email: {
type: DataType.STRING,
unique: true,
allowNull: false,
validate: {
notEmpty: true
}
};
}
}, {
classMethods: {
associate: (models) => {
Users.hasMany(models.Tasks);
}
}
});
return Users;
Mais adiante no capitulo 7.4 refatoramos o codigo acima mas não alteramos os campos conforme codigo abaixo:
import bcrypt from “bcrypt”;
module.exports = (sequelize, DataType) => {
const Users = sequelize.define(“Users”, {
// Os campos desse modelo foram criados no capítulo 5
}, {
hooks: {
beforeCreate: user => {
const salt = bcrypt.genSaltSync();
user.password = bcrypt.hashSync(user.password, salt);
}
},
classMethods: {
associate: models => {
Users.hasMany(models.Tasks);
},
isPassword: (encodedPassword, password) => {
return bcrypt.compareSync(password, encodedPassword);
}
}
});
return Users;
};
Ou seja no capitulo 5 não foi instruído a criar o campo password, necessario para o correto funcionamento
Obrigado