-1

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) {
  res.json({
    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.

Ajai Sandy
  • 107
  • 1
  • 2
  • 11

1 Answers1

4

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 = ['127.0.0.1'];

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

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

georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • Hi geroge, Thank you for help, is it possible that instead of IP address is there any package which allow me to use domain name? By the way I would try out the suggestion that you provided, Thanks. – Ajai Sandy Nov 03 '16 at 02:42
  • Client to server connections are done using IP address. The nodeJS DNS module has a method called `.reverse` which uses IP address to get an array of hostnames. – georgeawg Nov 03 '16 at 04:53
  • Hi george, I hosted my project in my server, now the problem is when I request my website it goes to my external ip ->Nginx(127.0.0.1)->api and I am getting the result. When I white-listed 127.0.0.1 am able to get response from when I simply enter the api GET function in my browser. Kindly provide me solution so solve my issue. Thanks – Ajai Sandy Nov 13 '16 at 13:33