This repository have all pilot projects which are used in the ebook: Building APIs with Node.js.
Caio Ribeiro Pereira - https://crpwebdev.github.io
Some stuffs of the book Building APIs with Node.js
This repository have all pilot projects which are used in the ebook: Building APIs with Node.js.
Caio Ribeiro Pereira - https://crpwebdev.github.io
Hi, thanks for your book. I have been battling with this error TypeError: db.models[key].associate is not a function
. I have tried to resolve but all to no avail. Can you help out?
When I run your code about mocha test,in the directory test/routes/
if a test file follow closely token.js
, it will always throw an error:
Routes: Users
GET /user
status 200
Unhandled rejection SequelizeUniqueConstraintError: Validation error
at Query.formatError (/home/jadestrong/Documents/building-apis-with-nodejs/ntask-api/node_modules/sequelize/lib/dialects/sqlite/query.js:337:14)
at Statement.afterExecute (/home/jadestrong/Documents/building-apis-with-nodejs/ntask-api/node_modules/sequelize/lib/dialects/sqlite/query.js:112:29)
at Statement.replacement (/home/jadestrong/Documents/building-apis-with-nodejs/ntask-api/node_modules/sqlite3/lib/trace.js:20:31)
1) "before each" hook for "returns an authenticated user"
11 passing (4s)
1 failing
1) Routes: Users "before each" hook for "returns an authenticated user":
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
after test,I found the reason is :
describe("Routes: Token", () => {
const Users = app.db.models.Users;
describe("POST /token", () => {
beforeEach(done => {
Users
.destroy({where: {}})
.then(() => Users.create({
name: "John",
email: "[email protected]",
password: "12345"
}))
.then(done()); // here should be `.then(() => done())`
});
You can test it, and change the book's content about it.
English is not good, forgive me
Hello,
many thanks for the tutorial, this is very very helpful for a newbie like me. I am able to follow the complete code and able to make it run. The only issue I am facing is related to test.
I downloaded the repository and installed all packages.
entered the following command
npm test
D:\XAMPP\htdocs\nodewebservice\building-apis-with-nodejs-master\ntask-api>npm test
> [email protected] test D:\XAMPP\htdocs\nodewebservice\building-apis-with-nodejs-master\ntask-api
> SET NODE_ENV=test mocha test/**/*.js
D:\XAMPP\htdocs\nodewebservice\building-apis-with-nodejs-master\ntask-api>
There is no test executed. Please help me solve this,
This is not an issue, per se, but it's unclear where else to publish some ideas.
Chapter 7 is a great addition to the book in terms of taking what went before and then providing authentication. However, in a previous chapter you showed people how to use Postman to test the API.
With the addition of authentication, however, that no longer works. Or, rather, you have to use Postman to authenticate as well by providing an authentication type. That would ideally be a good thing to have at the end of chapter 7 so that people can consistently understand how to interact with the API when there is authentication.
Just a thought.
How can I customize error raised from app.auth.authenticate(), my error handler is within .("libs/middlewares.js"),but this occurs after db.auth
Hi,
first of all, i really like your ebook! It's great!
But i got the same issue as has already been described here ( http://forum.casadocodigo.com.br/t/construindo-apis-rest-com-nodejs-consideracoes-durante-o-estudo/82 ) but my Portuguese is not so good ;).
I also attached my npm-debug.log.
Is it possible that you can explain some tips to solve this problem here?
I would be very grateful.
I work with this fork: https://github.com/ArnaudValensi/node-express-sequelize-es2015
Your code also have same snipped, so i post issue here.
I ve got some bluebird warnings like "Warning: a promise was created in a handler at ... but none were returned from it" - for ex, code in auth.js:
const strategy = new Strategy(params, (payload, done) => {
Users.findById(payload.id)
.then(user => {
if (user) {
return done(null, { // << -- here is problem
id: user.id,
email: user.email,
});
}
return done(null, false);
})
.catch(error => done(error, null));
});
Here is explanation of problem in issue thread: petkaantonov/bluebird#508
Possible fix:
const strategy = new Strategy(params, (payload, done) => {
Users.findById(payload.id)
.then(user => {
if (user) {
return { // << -- fix
id: user.id,
email: user.email,
});
}
return false;
})
.asCallback(done)
.catch(error => done(error, null));
});
but I'm currently getting a bug in the code. It is below
Unhandled rejection SequelizeDatabaseError: SQLITE_ERROR: table Tasks has no column named user_id
at Query.formatError (C:\Users\D-BELOVED\Desktop\ntask-api\node_modules\sequelize\lib\dialects\sqlite\query.js:348:14)
at afterExecute (C:\Users\D-BELOVED\Desktop\ntask-api\node_modules\sequelize\lib\dialects\sqlite\query.js:112:29)
at Statement.errBack (C:\Users\D-BELOVED\Desktop\ntask-api\node_modules\sqlite3\lib\sqlite3.js:16:21)
I have written the code exactly the same way it was in the book, literarily lifted it. Other tests are running except this particular ones.
and I have sqlite3 version 3.1.13 installed, couldn't install v 3.1.1 because it was always throwing error too
Thanks for your prompt reply
iam having following error when i hit /tasks URL
AfterContent Security Policy: The page’s settings blocked the loading of a resource at self (“default-src http://localhost:3000”)
Here is the console message:
:3001/js/app.js:718 Uncaught TypeError: Cannot read property 'addEventListener' of null
at Signin.signupClick (:3001/js/app.js:718)
at Signin.addEventListener (:3001/js/app.js:682)
at Signin.render (:3001/js/app.js:676)
at App.init (:3001/js/app.js:593)
at window.onload (:3001/js/app.js:875)
the attached file contains the ntask-web/public/js/app.js file the message is referring to:
app.zip
I have copied the files src/components/signin (and signup) and src/templates/signin (and signup) directly from the git hub source to eliminate that as a typo.
Any clues on where I should be looking?
Nice tutorial once again. Seems you missed the user_id column in the Task table. I tried to add it but still my test is still failing. Will keep on trying though
Running npm test deletes all data from the .sqlite file even though the test config sets a different db from the development config.
Can I please know where does app.db comes from?
app.db.sync().done(() => {
app.listen(app.get('port'), ()=>{
return console.log(`NTask API - Port ${app.get('port')}`);
});
});
Later, it got switched to app.db.sequelize.
app.db.sequelize.sync().done(() => {
app.listen(app.get('port'), ()=>{
return console.log(`NTask API - Port ${app.get('port')}`);
});
});
Hi,
first of all, i really like your ebook! It's great!
when i install with sudo npm install
But i got a error,here is
npm-debug.txt
i searched baidu and google ,deleted ./node-gyp and reinstalled it ,i got the error too .
i installed [email protected] it doesn't work too.
zyxdeMacBook-Pro:ntask-api zyx$ python --version
Python 2.7.10
zyxdeMacBook-Pro:ntask-api zyx$ npm -v
3.10.9
zyxdeMacBook-Pro:ntask-api zyx$ node -v
v7.2.0
zyxdeMacBook-Pro:ntask-api zyx$ node-gyp rebuild
gyp info it worked if it ends with ok
gyp info using [email protected]
gyp info using [email protected] | darwin | x64
gyp info spawn /usr/bin/python
gyp info spawn args [ '/usr/local/lib/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args 'binding.gyp',
gyp info spawn args '-f',
gyp info spawn args 'make',
gyp info spawn args '-I',
gyp info spawn args '/Users/zyx/code/building-apis-with-nodejs/ntask-api/build/config.gypi',
gyp info spawn args '-I',
gyp info spawn args '/usr/local/lib/node_modules/node-gyp/addon.gypi',
gyp info spawn args '-I',
gyp info spawn args '/Users/zyx/.node-gyp/7.2.0/include/node/common.gypi',
gyp info spawn args '-Dlibrary=shared_library',
gyp info spawn args '-Dvisibility=default',
gyp info spawn args '-Dnode_root_dir=/Users/zyx/.node-gyp/7.2.0',
gyp info spawn args '-Dnode_gyp_dir=/usr/local/lib/node_modules/node-gyp',
gyp info spawn args '-Dnode_lib_file=node.lib',
gyp info spawn args '-Dmodule_root_dir=/Users/zyx/code/building-apis-with-nodejs/ntask-api',
gyp info spawn args '--depth=.',
gyp info spawn args '--no-parallel',
gyp info spawn args '--generator-output',
gyp info spawn args 'build',
gyp info spawn args '-Goutput_dir=.' ]
gyp: binding.gyp not found (cwd: /Users/zyx/code/building-apis-with-nodejs/ntask-api) while trying to load binding.gyp
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack at ChildProcess.onCpExit (/usr/local/lib/node_modules/node-gyp/lib/configure.js:305:16)
gyp ERR! stack at emitTwo (events.js:106:13)
gyp ERR! stack at ChildProcess.emit (events.js:191:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
gyp ERR! System Darwin 16.1.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/bin/node-gyp" "rebuild"
gyp ERR! cwd /Users/zyx/code/building-apis-with-nodejs/ntask-api
gyp ERR! node -v v7.2.0
gyp ERR! node-gyp -v v3.4.0
gyp ERR! not ok
zyxdeMacBook-Pro:ntask-api zyx$
http://stackoverflow.com/questions/20911930/when-trying-to-configure-or-rebuild-node-gyp-getting-errors-mac-osx-mavericks i tried all the posibility in this question , no one works for me .
i'm not sure if i offered enough info or not, if you need more info to position the error , let me know, thank you very much.
Is it possible that you can explain some tips to solve this problem here?
I would be very grateful.
Hello caio-ribeiro-pereira,
I am impressed the way the whole code and documentation is put together. It is easy to follow even for a beginner like me.
Kindly include the following in tutorial
I followed the steps laid out in the pdf and used passport js lib for authenticating the endpoints. However, I am stuck after I placed the app.auth.authenticate() in route.all() middleware. It's showing me ### Unauthorized as it should. How do I use the web token in Postman to view the tasks list? I am getting response from /token/ route, when I am providing a jsonified email and password. Not sure how to resolve this issue. When I remove app.auth.authenticate() I am able to see the task list (or create).
app.route('/tasks')
.all(app.auth.authenticate())
.get((req, res) => {
//Tasks: List tasks.
Tasks.findAll({
where: { user_id: req.user.id }
}).then(
result => res.json(result)
).catch(error => {
res.status(412).json({msg:error.message})
});
})
.post((req, res) => {
//Save Tasks: Save Task.
req.body.user_id = req.user.id;
Tasks.create(req.body).then(
result => res.json(result)
).catch(error => {
res.status(412).json({msg:error.message})
});
});
I've gotten to the end of chapter 12 and tried to test it but have gotten hung up on this error. It is coming from the code that ends up in the browser, which is produced by babel, I assume, so I'm having a hard time identifying the source of it. It's hard enough troubleshooting my own code but code that's written by a machine is even harder. Here what I see in the Chrome debbugger:
window.onload = function () {
var main = document.querySelector("main");
new _app2.default(main).init();
};
The breakpoint is on the line "new _app2.default(main).init();" The browser is saying that _app2.default is not a constructor. Any ideas where I can look for the source of this error. I've checked all of my codes and it looks correct.
If you follow the book through to the end up chapter 8, the following test seems to always fail:
Routes: Token
POST /token
status 200
1) returns authenticated user token
It always says:
Uncaught AssertionError: expected {} to contain key 'token'
+ expected - actual
-[]
+[
+ "token"
+]
That said, you get this by following the book code exactly. Checking out the current repo will not show that issue because it contains all changes. I've been doing a branch per chapter, which is how I'm able to isolate certain issues.
I am just curious, how does express instance is accessible inside routes directory?
module.exports = app =>{
app.get('/', (req, res)=>{
res.json({'status': 'NTask API'});
});
};
app variable is defined in index.js file in root directory of the project but we use app in routes directory in both routes. Can you please explain this? Thanks in advance.
Hello everyone, i am a newbie. I'm following this tutorial and i have a problem as below.
/home/anh/Documents/nodejs/pilot/ntask-api/libs/middlewares.js:13
app.use(app.auth.initialize());
^
TypeError: app.auth.initialize is not a function
at Function.module.exports (/home/anh/Documents/nodejs/pilot/ntask-api/libs/middlewares.js:7:22)
at Consign.into (/home/anh/Documents/nodejs/pilot/ntask-api/node_modules/consign/lib/consign.js:240:17)
at Object.<anonymous> (/home/anh/Documents/nodejs/pilot/ntask-api/index.js:13:6)
Can you tell me what i am missing? Thank you!
On page 7 under the section, What does NPM do?, you wrote: "+149 million downloads are made daily and +3.4 million downloads are made monthly."
Shouldn't 3.4 million i be 3.4 billion?
After cloning the repo, I try to run the app using:
$ npm start
And after doing that, I get the following dump:
> [email protected] start /home/pranjal/WebApps/nodejs-apis/ntask-api
> npm run apidoc && npm run clusters
> [email protected] apidoc /home/pranjal/WebApps/nodejs-apis/ntask-api
> apidoc -i routes/ -o public/apidoc
info: Done.
> [email protected] clusters /home/pranjal/WebApps/nodejs-apis/ntask-api
> babel-node clusters.js
fs.js:794
return binding.mkdir(pathModule._makeLong(path),
^
Error: EEXIST: file already exists, mkdir 'logs'
at Error (native)
at Object.fs.mkdirSync (fs.js:794:18)
at Object.<anonymous> (/home/pranjal/WebApps/nodejs-apis/ntask-api/libs/logger.js:5:6)
at Module._compile (module.js:410:26)
at loader (/home/pranjal/WebApps/nodejs-apis/ntask-api/node_modules/babel-register/lib/node.js:144:5)
at Object.require.extensions.(anonymous function) [as .js] (/home/pranjal/WebApps/nodejs-apis/ntask-api/node_modules/babel-register/lib/node.js:154:7)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
Cluster 30492 disconnected
Cluster 30492 is dead
NTask API - Port 3000
Cluster 30498 connected
NTask API - Port 3000
Cluster 30497 connected
NTask API - Port 3000
Cluster 30487 connected
NTask API - Port 3000
Cluster 30509 connected
But when I open the default URL localhost:3000
then a server error shows up in my browser. When I try to curl
into the default URL, I get this:
$ curl localhost:3000
curl: (52) Empty reply from server
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.