seanpmaxwell / express-generator-typescript

Create a new express app similar to express-generator but with TypeScript

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

A little help with sending only json response

cunundrummer opened this issue · comments

Hi, I am trying out this generator, and so far, I like what I see. Thing is, I as I am trying to implement my routes, which are similar to the users (res.status(OK).json({users}), but mine never seems to call.

I checked the BaseRouter through console.log and see the regex of my route. For simplicities sake, I have added one route to the index.ts file (where the routes are). So under the

import UserRouter from './routes;
I added my own
import MyThingRouter from './routes; and also router.use('/mything', MyThingRouter);
and myThingRouter does an export default router too.

So still, I got the default users page (html). Thing is, I don't want to send an html/frontend stuff. Only JSON.
I compared this app to my expressjs-generator generated app, and noticed a few things I need clarification on.

  1. Like my ide shows the proper router when I hover over BaseRouter. I'm guessing that it was declared in a 'short-hand' way like instead of using import * as BaseRouter... because of default?
    Either way, BaseRouter seem to know about my route.

  2. How would I be able to send out my json from my routes. In the server.ts, I see the way the example app does it is through sending a template file that has js to 'call/fetch' the user json. I just want to call my route method directly from the browser address. Like
    localhost:3000/mything/all should send my json data.

If I comment out the provided server.js app.get('*', (req, res)... near the end of the file, I get a 404 error "Cannot GET /mything/all". I would have thought that the
app.use('/api', BaseRouter) would handle the route. My expressjs app seems to handle it.

I just tried as of typing this, trying to implement the expressjs way, but the router doesn't seem to call my get method which is almost exactly like the user example in router.get('/all',...). Also, added raw json to res.json in my route, and removing promises because I am somewhat at a loss. Everything is back to default now.

TLdr; I followed the example code and also attempted to implement routing similar to my non-ts expressjs app, but cannot call my get method to return JSON only.

app.use('/api', BaseRouter) prepends 'api' to all the routes. Try calling '/api/mything/mythingroute'

Tried things this morning - including restarting the server - and whaddayaknow? It works. Thanks!