Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

  • Print
  • + Share This
This chapter is from the book

Creating Posts via the API

Now let’s build the POST endpoint for creating posts. Add this endpoint to server.js:'/api/posts', function (req, res) {
  console.log('post received!')

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.

  • + Share This
  • 🔖 Save To Your Account