- The Stock Endpoint
- Creating Posts via the API
- MongoDB Models with Mongoose
- Using Mongoose Models with the POST Endpoint
- Next Steps
Creating Posts via the API
Now let’s build the POST endpoint for creating posts. Add this endpoint to server.js:
app.post('/api/posts', function (req, res) { console.log('post received!') console.log(req.body.username) console.log(req.body.body) res.send(201) })
This is just a request that checks to see whether you’re reading the data properly. The client would receive only the HTTP status code 201 (created). It’s good to build a lot of these stubbed-out sorts of logic to check to see whether your plumbing is in order when building MEAN applications. Because you can’t test a POST request using the browser, you should check to see whether it is working using curl:
curl -v -H "Content-Type: application/json" -XPOST --data "{\"username\":\"dickeyxxx\", \"body\":\"node rules!\"}" localhost:3000/api/posts
If you are unfamiliar with curl, this says “Make a POST request to localhost:3000/api/posts. Be verbose.” Setting your Content-Type header to json includes the JSON document as the body.
The Content-Type header is necessary to be able to parse this content into the friendly req.body.username objects from the JSON.
If the command line isn’t your thing, you can do this same thing using the great Postman app for Chrome to test APIs. Regardless of what method you use, it is crucial you test your APIs using stub clients like this rather than building your app in lockstep.