ashish paralkar
ashish paralkar

Reputation: 33

Cannot GET from endpoint in Express.js

I have two endpoints in my express app, one is /ping - doesnt take any parameters and is working fine, the other is /posts which takes one mandatory parameter 'tag' and two optional ones 'sortBy' and 'direction'.

The app starts, and in Postman the /ping works fine on GET, however the /posts is not working as expected

const express = require('express')
const apicache = require('apicache')
const bodyParser = require('body-parser');
const PORT = process.env.PORT || 8080; //use 8080 or use whatever Heroku gives you
const { ping, getPosts } = require('./controller')

const app = express()
//app.use(express.json())
app.use(bodyParser.json())
const cache = apicache.middleware; //as described on https://www.npmjs.com/package/apicache

app.get('/api/ping', ping) //the first requirement, a ping endpoint


app.get('/api/posts/:tag/:sortBy?/:direction?', cache('5 minutes'), getPosts) //second requirement, an endpoint that fetches posts from the hatchways website

app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`)
})

Now as per Express's docs I would expect the url "localhost:8080/api/posts?tag=tech" to work, however Postman says cannot GET /api/posts What does work is hitting the url "localhost:8080/api/posts/tag/tech" which is not what this app is expected to respond to.

I think I am missing something about URL specifications. I do need it to work on "localhost:8080/api/posts?tag=tech" and not "localhost:8080/api/posts/tag/tech"

Help is appreciated, thank you.

Upvotes: 0

Views: 1736

Answers (1)

Take-Some-Bytes
Take-Some-Bytes

Reputation: 952

Looks like you are a bit confused about queries and route parameters.

A query is a part of the URL, and it looks like this:

https://example.com/api/posts?tag=tech&this=that+something

While route parameters are (kind of) similar, they are not the same. It looks like a regular URL, but parts of it could be different.

Currently, you are defining your express route to accept route parameters, and not queries. To make it work on queries, just do this:

// Remove the 3 route parameters, and do this instead.
app.get('/api/posts', cache('5 minutes'), getPosts);

And, make sure you use req.query in your getPosts controller:

exports.getPosts = function(req, res) {
  // Get whatever you need in req.query
  // In your case you need tag, sortBy, and direction.
  const { tag, sortBy, direction } = req.query;

  // You API code.
}

Now, your express API should function as expected.

Upvotes: 1

Related Questions