Ajai Sandy Ajai Sandy - 1 year ago 155
Node.js Question

Make API Private / Enable cors option in angular fullstack generator

I am using angular fullstack generator for my web app, I want to make my api a private one, meaning the response should be provided only from my domain. If the api is used from a different domain it should not provide the response.

For this I used the following npm package https://www.npmjs.com/package/cors.

I have added the following code in my project.

'use strict';

var express = require('express');
var cors = require('cors');
var router = express.Router();
var app = express();

var corsOptions = {
origin: 'http://example.com'

router.get('/', cors(corsOptions), function(req, res, next) {
msg: 'This is CORS-enabled for only homefuly.com.'

module.exports = router;

The above code is placed in my server->api->test->index.js

when I hit the api http://localhost:9000/api/test I am able to see the response.I should only get response if my making request from example.com else it should throw an error message, kindly help to achieve this.

Thanks in advance.

Answer Source

I want to make my api a private one

Express can restrict connections based on IP address:

var express = require('express')
    , ipfilter = require('express-ipfilter').IpFilter
    , app = express.createServer()

// Whitelist the following IPs
var ips = [''];

// Create the server
app.use(ipfilter(ips, {mode: 'allow'}));

For more information,see NPM express-ipfilter Package INFO.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download