- Might get the following errors in console :
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
To resolve it, look for multiple res.status()
being sent from one request. Look for return
statements carefully too and handle it appropriately. Or look for conditional logic like if..else
blocks.
You can send a response to the client only once when you send more than one time that will generate the error
2. About ExpressJS' request
object parts :
req.body
- Generally used in POST/PUT requests when we need to send data to the server. Remember to useexpress.json()
middleware to parse request body else you'll get an errorreq.params
- These are properties attached to the url i.e named route parameters. You prefix the parameter name with a colon (:
) when writing your routes.
app.get('/giraffe/:number', (req, res) => {
console.log(req.params.number)
})
GET http://localhost:3000/giraffe/1
req.query
- Mostly used for searching,sorting, filtering, pagination, e.t.c. It written as key=value preceeded by?
. We can add multiple queries using&
operator in the URL.
GET http://localhost:3000/animals?page=10
GET http://localhost:3000/animals?page=10§ion=2
app.get('/animals', ()=>{
Animals.find(req.query)
console.log(req.query.page) // 10
})
- For data hosted on MongoDB Atlas, MongoDB offers an improved full-text search solution, Atlas Search, which has its own
$regex
operator. - For sorting, using mongoose
sort()
ref here. - Promises .then .catch and aysnc/await are 2 different things for aynshronous behaviouors so one must use any one.
- Signing JWT token and Verifying it must be done in same manner like the following :
// on login
console.log({ email }); // { email: 'meet@gmail.com' }
const token = jwt.sign({ email }, secret);
// on verification
const verification = jwt.verify(req.headers.authorization, secret);
console.log(verification); // { email: 'meet@gmail.com' }
return Developer.findOne({ email: verification.email })
OR the following... but this is avoided since we cant check the token type when using a combined authenticator like roleBasedAuthentication
middleware.
console.log(email); // meet@gmail.com
const token = jwt.sign(email, secret);
// on verification
const verification = jwt.verify(req.headers.authorization, secret);
console.log(verification); // meet@gmail.com
return Developer.findOne({ email: verification })
- Installed packages for testing as dev dependencies.
npm i -D mocha chai supertest nyc
- Created
/test
folder. - When creating
/test
folder, try to mimic the folder structure of the project in it. Mocha
is gonne look fortest
folder.- Enable mocha in the
.eslintrc.js
- Added test script in
package.json
and rannpm run test
. 1. 2. Also added a script for coverage and can run it throughnpm run test:cov
3. Be careful in naming and avoid typos. - To create a test we use
describe()
which describes a "suite"(a group of related test cases) with the given 'title' andcallback fn
containing nested suites. done()
function is used to handle asynchronous operations in test cases such as making HTTP requests, interacting with databases, or using timers, it's important to notify the testing framework when the asynchronous operations have completed.- This ensures that the test case doesn't complete prematurely or timeout before the asynchronous operations finish.
- It is typically passed as a parameter to the test case function, and it needs to be invoked to signal the completion of the test case.
- The testing framework waits for
done()
to be called before moving on to the next test case or completing the test suite. - If
done()
is not called at the end of test suite then an error like following can occur.
Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
- Ensure the URL paths of test cases are started with a slash like
/developers
otherwise the following error can come :
Error: ECONNREFUSED: Connection refused
.only
used withdecribe.only()
will run only that test suite..skip
used withdescribe.skip()
will skip that specific test suite.