I have this API built with Nodejs-Express:
app.get('/api/v1/:search', function(req, res){
var response = {}
res.contentType('application/json');
// process req.params['search']
// build and send response
res.send(response, response.status_code);
});
However, I need to make a client that will sit on another domain. How do I fix this code so it can be called through like JQuery $.ajax, etc.
Something like this should work:
//Middleware: Allows cross-domain requests (CORS)
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
//App config
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: 'secret' }));
app.use(express.methodOverride());
app.use(allowCrossDomain);
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With