I would like to be able to create REST APIs in a Nuxt app that I am making. I could use the express example, where Nuxt itself is just an express middleware, but that just makes using Nuxt a bit more complex to use.
I can currently create REST APIs, to a degree, by using the serverMiddleware
key in nuxt.config.js:
serverMiddleware: [
{
path: '/helloapi',
handler(req, res, next) {
res.setHeader("Content-Type", "application/json")
res.end(JSON.stringify({ this: 'is', a: 'test'}))
}
}
]
I can also create a Nuxt middleware
/middleware/api.js
export default function (context) {
let req = context.req
if (req) {
let res = context.res
if (req.url === '/myapi') {
res.setHeader("Content-Type", "application/json")
res.end(JSON.stringify({ message: 'Hello World' }))
}
}
}
and configure it in nuxt.config.js:
router: {
middleware: 'api'
}
Both of the above solutions allow me to create a REST API. However, they lack the power of express. So, I have to handle parsing routes, url parameters and REST arguments, like '/myapi/42', myself. This is not optimal, but doable.
In renderer.js
around line 17 there is a line that imports connect
import connect from 'connect'
If we change it to
import connect from 'express'
By using express, we could use it's full power to parse routes with parameters, such as "/user/paul/post/7", without writing our own parsing code. We would also get many other helpers, such as res.json()
, etc...
I made that change on a fork and did some limited testing on my app and it seems to work just fine. I'm not sure what other implications there are, so, just want run it by you.
Here are a couple of question I have: