有没有办法看谁调用了nodejs控制器?

时间:2018-05-28 07:11:14

标签: javascript node.js

我们有很多页面/网站调用不同的nodejs控制器。

示例:

//
// Get template data
//
$http({
    method: 'POST',
    url: globalSetting.serverURL + 'getMailTemplate',
    headers: { 'Content-Type': 'application/json' },
    data: {
        users:       $scope.vm.user,
        booking:     $scope.vm.booking
    }
}).then((response) => {
    // whatever
}

控制器是否有办法查看来电的来源?

调用哪个页面或哪个URL或哪个用户或??

1 个答案:

答案 0 :(得分:1)

如果您可以访问Node.js中的req对象,则可以从中获取一些有用的调用者详细信息,例如IP地址,位置等。

const express = require('express');
const geoip = require('geoip-lite');

var app = express();
app.set('trust proxy', true);

function getCallerDetails(req) {

    const geo = geoip.lookup(req.ip);

    const result = {
        ip: req.ip,
        browser: req.headers["user-agent"],
        language: req.headers["accept-language"],
        country: (geo ? geo.country: "Unknown"),
        region: (geo ? geo.region: "Unknown"),
        position: (geo ? geo.ll: "Unknown")
    }

    return result;
}

app.get('/getcallerdetails', function(req, res){


    let result = getCallerDetails(req);

    console.log('Headers: ' + JSON.stringify(result.headers));
    console.log('IP Address: ' + JSON.stringify(result.ip));
    console.log("Browser/User-Agent: " + result.browser);
    console.log("Language: " + result.language);
    console.log("Country: " + result.country);
    console.log("Region: " + result.region);

    console.log(result);

    res.status(200);
    res.header("Content-Type",'application/json');
    res.end(JSON.stringify(result, null, 4));
});

app.listen(3000);