I am very new to JS and I’m trying to create an API using node.js however I’m getting the error:
JavaScript
x
2
1
Uncaught error: invalid input syntax for type integer: "NaN"
2
The requests are fine when I do a GET and POST request but I’m having trouble with the PUT and DELETE. I get the same error with both requests. Here is my code:
JavaScript
1
70
70
1
const getProfiles = (request, response) => {
2
pool.query('SELECT * FROM profiles', (error, results) => {
3
if (error) {
4
throw error
5
}
6
response.status(200).json(results.rows)
7
})
8
}
9
10
const addProfiles = (request, response) => {
11
const {name, bio} = request.body
12
13
pool.query(
14
'INSERT INTO profiles (name, bio) VALUES ($1, $2) RETURNING id',
15
[name, bio],
16
(error) => {
17
if (error) {
18
throw error
19
}
20
response.status(201).json({status: 'success', message: 'Profile added.'})
21
})
22
23
}
24
25
const updateProfiles = (request, response) => {
26
const id = parseInt(request.params.id)
27
const {name, bio} = request.body
28
29
pool.query(
30
'UPDATE profiles SET name = $1, bio = $2 WHERE id = $3 RETURNING id',
31
[name, bio, id],
32
(error) => {
33
if (error) {
34
throw error
35
}
36
response.status(202).json({status: 'success', message: 'Profile updated with ID: ${id}'})
37
})
38
}
39
40
const deleteProfiles = (request, response) => {
41
const id = parseInt(request.params.id)
42
43
pool.query(
44
'DELETE FROM profiles WHERE id = $1', [id],
45
(error, results) => {
46
if (error) {
47
throw error
48
}
49
response.status(203).send(`Profile deleted with ID: ${id}`)
50
})
51
}
52
53
app
54
.route('/profiles')
55
// GET endpoint
56
.get(getProfiles)
57
// POST endpoint
58
.post(addProfiles)
59
//UPDATE endpoint
60
.put(updateProfiles)
61
// DELETE endpoint
62
.delete(deleteProfiles)
63
64
65
66
// Start server
67
app.listen(process.env.PORT || 3002, () => {
68
console.log(`Server listening`)
69
})
70
I am very much new to this and if you spot where I went wrong I would very much appreciate and explanation for me to better understand it and never make this mistake again. Thank you.
Advertisement
Answer
As far as I can see, req.params.id is undefined, because you are not telling express that route should receive a param.
Change this:
JavaScript
1
11
11
1
app
2
.route('/profiles')
3
// GET endpoint
4
.get(getProfiles)
5
// POST endpoint
6
.post(addProfiles)
7
//UPDATE endpoint
8
.put(updateProfiles)
9
// DELETE endpoint
10
.delete(deleteProfiles)
11
To this:
JavaScript
1
14
14
1
app
2
.route('/profiles')
3
// GET endpoint
4
.get(getProfiles)
5
// POST endpoint
6
.post(addProfiles)
7
8
app
9
.route('/profiles/:id') // :id means we are expecting that param
10
//UPDATE endpoint
11
.put(updateProfiles)
12
// DELETE endpoint
13
.delete(deleteProfiles)
14
And when you do the PUT or DELETE request, the endpoint should look like this: /profiles/