Do you mind showing me the complete code you wrote with fine-rest?
This code is at the top of the file:
import { JsonRoutes } from 'fine-rest/json-routes';
JsonRoutes.setResponseHeaders({
"content-type": "application/json; charset=utf-8"
});
JsonRoutes.setResponseHeaders({
"Cache-Control": "no-store",
"Pragma": "no-cache",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, PUT, POST, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With"
});
JsonRoutes.Middleware.use('api/packages/v1/', (req, res, next) => {
const authUserId = req.userId;
if (!authUserId) {
JsonRoutes.sendResult(res, {
code: 401,
data: {
result: "ERROR"
}
});
}
next();
});
And this code is at the bottom of the same file:
JsonRoutes.add('POST', 'api/packages/v1/test', (req, res) => {
...
}
UPDATE: I get an error if I call next()
after the sendResult()
above:
Exception in callback of async function: Error: Can't set headers after they are sent.
If I make the call to http://localhost:3000/api/packages/v1/test
with the code above, the route api/packages/v1/test
will always run, even if sendResult()
in the middle ware is called. I donât want this, I want the middleware to kick them out of the process and return a 401 to the client if theyâre not authâd.
If I donât call next() if there is an error, and just call sendResult, then the âapi/packages/v1/testâ is never called, which is the result I want â except the statusCode is incorrect.
JsonRoutes.Middleware.use('api/packages/v1/', (req, res, next) => {
const authUserId = req.userId;
if (!authUserId) {
JsonRoutes.sendResult(res, {
code: 401,
data: {
result: "ERROR"
}
});
}
else {
next();
}
});
The above works, but the statusCode is not present, I get this result:
{
"result": "ERROR"
}