Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return JSON in stead of HTML when validation fails #129

Open
ghost opened this issue Aug 28, 2017 · 2 comments
Open

Return JSON in stead of HTML when validation fails #129

ghost opened this issue Aug 28, 2017 · 2 comments

Comments

@ghost
Copy link

ghost commented Aug 28, 2017

Hi guys,

Small (noob) question about swaggerize-express

It's awesome swaggerize-express validates incoming requests against the swagger schema. But I was wondering, how can I customise the response in not returning HTML formatted response, but a JSON response when validation fails?

Regards.

@gonenduk
Copy link

gonenduk commented Nov 1, 2017

The validation is done in a middleware function in the route system. It simply calls the next one with an error if it finds anything. This is the standard express way.
For example, if your api is under /api - add this as the last route declared:
app.use('/api', (err, req, res, next) => {
res.status(err.status).json(err);
});

@ghost
Copy link
Author

ghost commented Dec 18, 2017

Ok, what you're trying to say is:

According to the readme of swaggerize-express:

var http = require('http');
var express = require('express');
var swaggerize = require('swaggerize-express');

app = express();

var server = http.createServer(app);

app.use(swaggerize({
    api: require('./api.json'),
    docspath: '/api-docs',
    handlers: './handlers'
}));

server.listen(port, 'localhost', function () {
    app.swagger.api.host = server.address().address + ':' + server.address().port;
});

I should add the following (just before server.listen()), like so (when base path is /api):

var http = require('http');
var express = require('express');
var swaggerize = require('swaggerize-express');

app = express();

var server = http.createServer(app);

app.use(swaggerize({
    api: require('./api.json'),
    docspath: '/api-docs',
    handlers: './handlers'
}));

app.use('/api', (err, req, res, next) => {
  res.status(err.status).json(err);
});

server.listen(port, 'localhost', function () {
    app.swagger.api.host = server.address().address + ':' + server.address().port;
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant