I created an API endpoint to handle user account creation in my Next.js app, and I am using knex.js to handle my queries, but I still get this error:
JavaScriptx21API resolved without sending a response for /api/users/create, this may result in stalled requests.
2
My code in /pages/api/users/create.js
:
JavaScript
1
24
24
1
import { hash } from 'bcrypt';
2
import knex from '../../../knex';
3
4
export default async function regiterUser(req, res) {
5
if (req.method === 'POST') {
6
try {
7
hash(req.body.password, 10, async function (_, hash) {
8
await knex('users').insert({
9
name: req.body.name,
10
email: req.body.email,
11
role: 'user',
12
allowed: true,
13
password: hash,
14
});
15
res.end();
16
});
17
} catch (err) {
18
res.status(err).json({});
19
}
20
} else {
21
res.status(405);
22
}
23
}
24
Advertisement
Answer
actually the bcrypt hash function is an async function, it returns a promise to be either resolved with the encrypted data salt or rejected with an Error.
JavaScript
1
23
23
1
import knex from '../../../knex';
2
3
export default async function regiterUser(req, res) {
4
if (req.method === 'POST') {
5
try {
6
const hashed = await hash(req.body.password, 10);
7
await knex('users').insert({
8
name: req.body.name,
9
email: req.body.email,
10
role: 'user',
11
allowed: true,
12
password: hashed,
13
});
14
res.status(200).end();
15
} catch (err) {
16
res.status(err).json({});
17
}
18
} else {
19
res.status(405);
20
res.end();
21
}
22
}
23