|
1 | 1 | So far, we have only made GET requests to our server. A POST request can send data securely through the request body. In order to make POST requests, first we need to include the "body-parser" library from our node_modules (included with express). Add these lines after the app variable: |
| 2 | + |
2 | 3 | ```javascript |
3 | 4 | const bodyParser = require('body-parser'); |
4 | 5 | app.use(bodyParser.json()); |
@@ -26,6 +27,66 @@ app.post('/login',function(req,res){ |
26 | 27 | }) |
27 | 28 | } |
28 | 29 | }) |
| 30 | +``` |
| 31 | + |
| 32 | +Your entire file should look like this now: |
| 33 | + |
| 34 | +```javascript |
| 35 | +const express = require('express'); |
| 36 | +const app = express(); |
| 37 | +const bodyParser = require('body-parser'); |
| 38 | + |
| 39 | +app.use(bodyParser.json()) |
| 40 | + |
| 41 | +const mockUserData=[ |
| 42 | + {name:'Mark'}, |
| 43 | + {name:'Jill'} |
| 44 | +] |
| 45 | + |
| 46 | +app.get('/users',function(req,res){ |
| 47 | + res.json({ |
| 48 | + success: true, |
| 49 | + message: 'successfully got users. Nice!', |
| 50 | + users: mockUserData |
| 51 | + }) |
| 52 | +}) |
| 53 | +// colons are used as variables that be viewed in the params |
| 54 | +app.get('/users/:id',function(req,res){ |
| 55 | + console.log(req.params.id) |
| 56 | + res.json({ |
| 57 | + success: true, |
| 58 | + message: 'got one user', |
| 59 | + user: req.params.id |
| 60 | + }) |
| 61 | +}) |
| 62 | + |
| 63 | +app.post('/login',function(req,res){ |
| 64 | + // Typically passwords are encrypted using something like bcrypt before sending to database |
| 65 | + const username=req.body.username; |
| 66 | + const password=req.body.password; |
| 67 | + |
| 68 | + // This should come from the database |
| 69 | + const mockUsername="billyTheKid"; |
| 70 | + const mockPassword="superSecret"; |
| 71 | + |
| 72 | + if (username===mockUsername && password===mockPassword){ |
| 73 | + // In practice, use JSON web token sign method here to make an encrypted token |
| 74 | + res.json({ |
| 75 | + success: true, |
| 76 | + message: 'password and username match!', |
| 77 | + token: 'encrypted token goes here' |
| 78 | + }) |
| 79 | + } else { |
| 80 | + res.json({ |
| 81 | + success: false, |
| 82 | + message: 'password and username do not match' |
| 83 | + }) |
| 84 | + } |
| 85 | + |
| 86 | +}) |
| 87 | + |
| 88 | +app.listen(8000,function(){console.log('server is listening')}) |
| 89 | + |
29 | 90 | ``` |
30 | 91 | Time to commit our changes! |
31 | 92 | ``` |
|
0 commit comments