moleculer-web
moleculer-web copied to clipboard
500 Status Code for ServiceNotFoundError Using Express Middleware
I'm getting a 500 error code for ServiceNotFoundError while using express in middleware mode(settings.server = false). I experienced this on both 0.9.0 + 0.9.1. Moleculer docs state this should be a 404. Not a big deal but thought I'd point it out.
https://moleculer.services/docs/0.14/errors.html
started() { const app = express(); app.use("/", this.express()); }
I would like to add that setting mappingPolicy to 'restrict' changes the response to a 404.
Could you make a reproduce example?
I'm having the same issue, using:
"moleculer": "^0.14.10",
"moleculer-web": "^0.9.0",
Here's is the sample code:
const { ServiceBroker } = require('moleculer')
const express = require('express')
const ApiService = require('moleculer-web')
const broker = new ServiceBroker({ logger: console })
const svc = broker.createService({
name: 'api',
mixins: ApiService,
settings: {
server: false
}
})
const app = express()
app.use('/', svc.express())
app.listen(3000, err => {
if (err) { return console.error(err) }
})
broker.start()
And when calling a non existent url a 500 is returned instead of a 404.
# curl -I http://localhost:3000/some-nonexistent-url
HTTP/1.1 500 Internal Server Error
X-Powered-By: Express
X-Request-ID: 61cb2099-d27d-4275-b09d-ff79ed92f178
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Content-Length: 748
Date: Thu, 05 Nov 2020 20:33:15 GMT
Connection: keep-alive
If I run moleculer-web without express, in middleware mode, the result is as expected (a 404).
The problem is that Express builtin error-handler doesn't use the err.code
in the MoleculerError
s. To convert it, use something similar error handler for Express:
const { ServiceBroker } = require("moleculer");
const { MoleculerError } = require("moleculer").Errors;
const express = require("express");
const ApiService = require('moleculer-web')
const broker = new ServiceBroker({ logger: console });
const svc = broker.createService({
name: "api",
mixins: ApiService,
settings: {
server: false
}
});
const app = express();
app.use("/", svc.express());
app.use("/", (err, req, res, next) => {
if (err instanceof MoleculerError) {
return res.status(err.code).json(err);
}
next(err);
});
app.listen(3000, err => {
if (err) { return console.error(err); }
});
broker.start();
Thanks @icebob! Didn't see this on the docs.